哈斯克尔空荡荡的空间 [英] empty space work-around in haskell

查看:125
本文介绍了哈斯克尔空荡荡的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用Haskell做关于I / O和其他一些东西的小程序,并且我出来了一些有趣的东西。我想知道在一个文件中,我们可以处理空行吗?例如,我们可以计算空行的数量,还是可以在两条空行之间检索数据?如果是的话,我们如何才能实现这样的代码片段?我对haskell非常陌生,它让我很难理解语言的语法,所以我真的需要一些帮助来学习它。我试过了;

  readFile/tmp/foo.txt>> = print。长度 。过滤器(=='\\\
');

但这只是按照预期计算每一行。我如何消除非空行,并按照我的意愿去做其余的一些过程? 解决方案

如果你是新手对于Haskell而言,没有很好的理由将代码编写成像示例代码片段一样紧凑。我会这样写:

  ex1 = do 
contents< - readFileTest.hs
let noLines = length(filter(=='\\\
')contents)
print noLines





下一步是探索 Prelude :有一个叫做 lines ,它会将文本分成几行。所以让我们分成几行并删除空行:

  ex2 = do 
contents< - readFileTest。 hs
let nonempty = filter(/ =)(lines contents)
print(length nonempty)

这里 nonempty 是你列出的行( :: [String] )可以做进一步处理。


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?

解决方案

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.

这篇关于哈斯克尔空荡荡的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆