6

I would like to remove the whitespace located after \n.

For instance, username 123\n ugas 423\n peter 23\n asd234 would become username 123\nugas 423\npeter 23\nasd234.

David Cain
  • 16,484
  • 14
  • 65
  • 75
nicholas
  • 2,581
  • 14
  • 66
  • 104
  • 6
    10 questions, 0 accepts? Please reconsider. All the answers couldn't have been *that* bad. –  Jun 23 '10 at 04:25

2 Answers2

16

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
  • 5,057
  • 24
  • 19
  • 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. – nicholas Jun 27 '10 at 03:10
5
f [] = []
f ('\n':' ':a) = f ('\n' : a)
f (a:b) = a : f b
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
  • 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 Jun 23 '10 at 04:57
  • Thanks for the tip; I changed my answer. – yfeldblum Jun 23 '10 at 05:08
  • 1
    Can you explain the solution ? Justice – nicholas Jun 23 '10 at 07:51
  • It takes a list of characters, and any time the list begins with a sequence, it replaces it with a and then re-processes the list. If the list does not begin with , 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 Jun 23 '10 at 16:14
  • 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. – nicholas Jun 25 '10 at 03:56
  • @peterwkc Haskell uses spaces to separate function names from their arguments (eg. "foo x y") unlike many other languages which use brackets and commas (eg. "foo(x, y)"). Here, "f" is a function with one argument. That argument is a list of characters (a string). We can use recursion as long as the string is getting shorter. "f []" is the non-recursive base case, "f ('\n':' ':a)" recurses on "('\n':a)" which is one char shorter, "f (a:b)" recurses on "b" which is one char shorter. "x:y:z" is the syntax for a list. – Warbo Dec 20 '13 at 11:50