Haskell文件阅读 [英] Haskell file reading
问题描述
我刚刚开始学习Haskell,并且在尝试弄清文件阅读是如何工作的时候遇到了很多麻烦。
例如,我有一段文字文件test.txt它包含一些数字,如:
32 4
2 30
300 5
我想要阅读每行,然后评估每个单词并添加它们。
因此,我试图做到这样的事情:
import System.IO
import Control .Monad
main = do
let list = []
句柄< - openFiletest.txtReadMode
contents< - hGetContents句柄
单字< - (单词内容)
列表< -f单字
打印列表
h关闭句柄
f :: [字符串] - > [Int]
f =地图阅读
我知道这是完全错误的,不知道如何正确使用语法。
任何帮助将不胜感激。
除了这个之外,还有一些很好的教程链接,其中包含示例和代码解释:
http:// learnyouahaskell.com/input-and-output 我已经读完了
不错的开始!唯一需要记住的是纯函数应用程序应该使用 let
来代替绑定< -
。
import System.IO
import Control.Monad
main = do
let list = []
句柄< - openFiletest.txtReadMode
contents< - hGetContents句柄
let singlewords =单词内容
list = f单词
print列表
h关闭句柄
f :: [String] - > [Int]
f =地图读取
这是需要做的最小变化编译并运行。在风格上,我有几条评论:
- 绑定
list
两次看起来有点阴暗。请注意,这并没有改变list
这个值 - 它反映了旧的定义。 - 内联纯函数更多!
- 如果可能的话,使用
readFile
比手动打开,阅读和关闭文件更可取。
执行这些更改会产生如下所示的结果:
main = do
内容< - readFiletest.txt
print。地图readInt。单词$ contents
- 或者,main = print。地图readInt。 words =<< readFiletest.txt
readInt :: String - > Int
readInt = read
I have just recently started learning Haskell and I am having a lot of trouble trying to figure out how the file reading works.
For example, I have a text file "test.txt" And it contains lines of numbers eg:
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 so far:
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. Any help will be greatly appreciated. As well as links to good tutorials that have examples and explanation of code except this one: http://learnyouahaskell.com/input-and-output I have read it fully
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:
- 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屋!