views:

93

answers:

2

Hello to all, i have a and i would like to remove the white Space after "\n" and next character is white space.

For instance, "username 123\n ugas 423\n peter 23\n asd234" become

"username 123\nugas 423\npeter 23\nasd234"

Please help.

Thanks.

+5  A: 
f [] = []
f ('\n':' ':a) = f ('\n' : a)
f (a:b) = a : f b
Justice
This solution only removes one space after each newline. If the intent is to remove all leading spaces after each newline (unclear from the description), this small change to your second line would do it: f ('\n':' ':a) = f ('\n':a)
Vineet
Thanks for the tip; I changed my answer.
Justice
Can you explain the solution ? Justice
peterwkc
It takes a list of characters, and any time the list begins with a <cr><space> sequence, it replaces it with a <cr> and then re-processes the list. If the list does not begin with <cr><space>, then it takes the first character off and appends the rest of the list (after processing it).This solution will definitely work, but I personally find the one mentioned below (the unlines.map(dropWhile isSpace).lines one) a little more idiomatic.
hdan
I understand your explanation. What is this called f ('\n':' ':a) in haskell ? Constant pattern. The recursion function only have two parameters f (a:b) = a : f b but the pattern has three parameters. I don't understand this.
peterwkc
+10  A: 

I am assuming you want to remove one or more whitespace characters at the beginning of each line, not just the first whitespace character. Also, I think you want to remove any kind of whitespace characters, like tabs, not just literal space characters.

import Data.Char

stripLeadingWhitespace :: String -> String
stripLeadingWhitespace = unlines . map (dropWhile isSpace) . lines
Yitz
I understand your explanation. What is this called f ('\n':' ':a) in haskell ? Constant pattern. The recursion function only have two parameters f (a:b) = a : f b but the pattern has three parameters. I don't understand this.
peterwkc