我最近才开始学习 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
这是使事物编译和运行所需的最小更改。在风格上,我有几点意见:
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/