Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping newlines in Haskell

What is the (or is there an) idiomatic way to strip newlines from strings in Haskell? Or do I have to craft my own by finding the trailing newlines/spaces and then removing them?

EDIT: I'm looking for what Python's rstrip does, but don't need the optional "chars" argument:

string.rstrip(s[, chars])

Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

like image 372
qrest Avatar asked Jul 30 '10 16:07

qrest


3 Answers

Here's one simple implementation (adapted from Wikipedia):

import Data.Char (isSpace)
rstrip = reverse . dropWhile isSpace . reverse

There's also an rstrip already defined in Data.String.Utils.

(By the way, Hayoo! is a great resource for this kind of question: a search for rstrip takes you directly to Data.String.Utils.)

like image 59
Travis Brown Avatar answered Sep 17 '22 13:09

Travis Brown


I used this the other day:

Prelude> let trimnl = reverse . dropWhile (=='\n') . reverse
Prelude> trimnl ""
""
Prelude> trimnl "\n"
""
Prelude> trimnl "a\n"
"a"
Prelude> trimnl "a\n\n"
"a"
Prelude> trimnl "a\nb\n"
"a\nb"
like image 42
Simon Michael Avatar answered Sep 18 '22 13:09

Simon Michael


If this is for a typical file-reading application, then you should probably start with lines. This may allow you to avoid Data.String.Utils.rstrip completely:

> lines "one time\na moose\nbit my sister\n"
["one time", "a moose", "bit my sister"]

As you can see, lines takes the text of the entire file and properly turns each line into a string with no trailing newline. This means you can write a program like so:

main = mapM_ (putStrLn . process) . lines =<< readFile "foo.txt"
  where process :: String -> String
        process = -- your code here --
like image 35
Nathan Shively-Sanders Avatar answered Sep 16 '22 13:09

Nathan Shively-Sanders