file - Haskell 文件读取

标签 file haskell word

我最近才开始学习 Haskell,但在试图弄清楚文件读取的工作原理时遇到了很多麻烦。

例如,我有一个文本文件“test.txt”,其中包含带数字的行:

32 4
2 30
300 5

我想阅读每一行,然后评估每个单词并添加它们。

因此,我正在尝试做这样的事情:
import System.IO
import Control.Monad

main = do
        let list = []
        handle <- openFile "test.txt" ReadMode
        contents <- hGetContents handle
        singlewords <- (words contents)
        list <- f singlewords
        print list
        hClose handle

f :: [String] -> [Int]
f = map read

我知道这是完全错误的,但我根本不知道如何正确使用语法。

非常感谢任何帮助以及指向包含示例和代码解释的优秀教程的链接,this one 除外我已经完全阅读了。

最佳答案

不错的开始!唯一要记住的是纯函数应用程序应该使用 let而不是绑定(bind)<- .

import System.IO  
import Control.Monad

main = do  
        let list = []
        handle <- openFile "test.txt" ReadMode
        contents <- hGetContents handle
        let singlewords = words contents
            list = f singlewords
        print list
        hClose handle   

f :: [String] -> [Int]
f = map read

这是使事物编译和运行所需的最小更改。在风格上,我有几点意见:
  • 绑定(bind)list两次看起来有点阴暗。请注意,这不会改变值 list ——它反而掩盖了旧的定义。
  • 内联纯函数更多!
  • 如果可能,使用 readFile比手动打开、读取和关闭文件更可取。

  • 实现这些更改会给出如下结果:
    main = do  
            contents <- readFile "test.txt"
            print . map readInt . words $ contents
    -- alternately, main = print . map readInt . words =<< readFile "test.txt"
    
    readInt :: String -> Int
    readInt = read
    

    关于file - Haskell 文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7867723/

    相关文章:

    file - flutter 发送邮件附件

    date - 有日期的 Haskell 库吗?

    python - 如何用python找到最长的单词?

    python - 根据文件基名对文件夹和子文件夹中的所有文件进行排序

    python - python多久刷新一次文件?

    perl - 如何随机采样文件的内容?

    haskell - 使用 Writer monad 写入文件时如何避免内存问题?

    System T Combinator 语言的 Haskell 解释器

    solr - Apache Solr TermsComponent : How to prevent from splitting words after one character. 例如 "t-shirt"

    Python:独特的单词及其频率降序排列