Haskell 文件读取 [英] Haskell file reading
问题描述
我最近刚刚开始学习 Haskell,在试图弄清楚文件读取的工作原理时遇到了很多麻烦.
I have just recently started learning Haskell and I am having a lot of trouble trying to figure out how file reading works.
例如,我有一个包含数字行的文本文件test.txt":
For example, I have a text file "test.txt" containing lines with numbers:
32 4
2 30
300 5
我想阅读每一行,然后评估每个单词并添加它们.
I want to read each line and then evaluate each word and add them.
因此,我正在尝试做这样的事情:
Thus, I am trying to do something like this:
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
我知道这是完全错误的,但我根本不知道如何正确使用语法.
I know this is completely wrong, but I don't know how to use the syntax correctly at all.
非常感谢任何帮助以及包含示例和代码解释的优秀教程的链接,除了this一个,我已经读完了.
Any help will be greatly appreciated as well as links to good tutorials that have examples and explanation of code except this one which I have read fully.
推荐答案
不错的开始!唯一要记住的是,纯函数应用程序应该使用 let
而不是绑定 <-
.
Not a bad start! The only thing to remember is that pure function application should use let
instead of the binding <-
.
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
这是使事物编译和运行所需的最小更改.在风格上,我有几点意见:
This is the minimal change needed to get the thing to compile and run. Stylistically, I have a few comments:
- 绑定
list
两次看起来有点阴暗.请注意,这并没有改变list
值——而是隐藏了旧定义. - 更多内联纯函数!
- 如果可能,使用
readFile
比手动打开、读取和关闭文件更可取.
- Binding
list
twice looks a bit shady. Note that this isn't mutating the valuelist
-- it's instead shadowing the old definition. - Inline pure functions a lot more!
- When possible, using
readFile
is preferable to manually opening, reading, and closing a file.
实施这些更改会产生如下效果:
Implementing these changes gives something like this:
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
这篇关于Haskell 文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!