Deleting rows in Haskell

What is (or is) an idiomatic way of delimiting line strings from Haskell? Or do I need to create my own by finding trailing lines / spaces and then deleting them?

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

string.rstrip (s [, chars])

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

+6
string list haskell
source share
5 answers

Here is one simple implementation (adapted from Wikipedia ):

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

There is also rstrip already defined in Data.String.Utils .

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

+9
source share

Depending on what you mean:

  Prelude> filter (/ = '\ n') "foo \ n \ nbar \ n"
 "foobar"

 Prelude> words "foo \ n \ nbar \ n"
 ["foo", "bar"]

But this does not apply to a beautiful space. Therefore, perhaps not what you are looking for.

+3
source share

If this is a typical file reader, you should start with lines . This can allow you to completely avoid Data.String.Utils.rstrip :

 > 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 correctly turns each line into a line without a finite new line. This means that you can write a program like this:

 main = mapM_ (putStrLn . process) . lines =<< readFile "foo.txt" where process :: String -> String process = -- your code here -- 
+3
source share

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" 
+2
source share

There is a real world of haskell in chapter 4 that makes the break you want. You will need to insert the pieces together when done. http://book.realworldhaskell.org/read/functional-programming.html

Find "Warming Up: Hyphenated Text Lines" in the text.

+1
source share

All Articles