empty space work-around in haskell

拟墨画扇 提交于 2020-01-07 05:12:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!