问题
I've been making little baby programs with haskell about i/o and some other stuff and i came out something interesting. I wonder that in a file, can we process empty lines? For example can we count the number of empty lines or can we retrieve data between two empty lines? If so how can we implement such a code fragment? I am really new with haskell and it is getting me very hard to understand the syntax of the language so i really need some help to learn it. I tried like ;
readFile "/tmp/foo.txt" >>= print . length . filter (== '\n');
But this just counts every single line as expected. How can i eliminate non-empty lines and do some process with the rest as i want to?
回答1:
If you're new to Haskell there is no good reason to write as code as compact as your example snippet. I would put it like this
ex1 = do
contents <- readFile "Test.hs"
let noLines = length (filter (== '\n') contents)
print noLines
Which makes it slightly easier to see what's happening.
The next step is to explore the Prelude: there is a function called lines that will split a clump of text into lines. So let's split into lines and remove the empty ones:
ex2 = do
contents <- readFile "Test.hs"
let nonempty = filter (/= "") (lines contents)
print (length nonempty)
Here nonempty
is a list of lines (:: [String]
) that you can do further processing on.
来源:https://stackoverflow.com/questions/34345442/empty-space-work-around-in-haskell