【问题标题】:How t to count the number of words in a file in Haskell?Haskell如何计算文件中的单词数?
【发布时间】:2021-11-27 07:27:12
【问题描述】:

我正在关注这本书。 http://book.realworldhaskell.org/read/getting-started.html

我完全不知道如何计算文件中的字数。在尝试解决这个问题的过程中,我还注意到一些有趣的事情。

main = interact wordCount
    where wordCount input = show (length (input)) ++ "\n"

我注意到,如果没有“\n”字符,我会在数字末尾附加一个百分号。

main = interact wordCount
    where wordCount input = show (length (input))

所以我有 2 个问题,如果我不附加“\n”,为什么会得到百分号 字符以及如何计算文件中的所有单词?这比我学过的任何解释语言都要复杂得多。但我喜欢挑战。

在我的文本文件中,我删除了除一个之外的所有城市。 下面是我的txt文件的内容

Teignmouth, England

【问题讨论】:

标签: haskell


【解决方案1】:
  1. 您的 shell 实际上附加了一个 %,因为您的程序的输出不以换行符 (see here) 结尾。 POSIX 标准将“线”定义为以\n (see here) 结尾的东西。

  2. 函数words 就是你要找的:

main = interact wordCount
    where wordCount input = (show $ length $ words input) ++ "\n"

请注意,$ 运算符允许减少括号。这段代码是等价的:

main = interact wordCount
    where wordCount input = (show (length (words input))) ++ "\n"

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多