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.
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
.)
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"
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 --
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With