哈斯克尔空荡荡的空间 [英] empty space work-around in 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屋!