Haskell - 将包含数字的文件读入列表 [英] Haskell - Read a file containing numbers into a list
问题描述
所以我有一个这种格式的文本文件:
So I have a text file in this format:
1 3 4 5 1 3 9 12 5
假设此文件名为 numbers.txt
。
我想告诉Haskell从文件中读取,并将这些数字放在列表中。所以我最终得到:
I want to tell Haskell to read from the file, and put those numbers in a list. So I would end up with:
[1,3,4,5,1,3,9,12,5]
我真的不明白怎么做,而且我一直在搜索。我知道我需要使用getLine,但那又怎么样?我会使用函数将该字符串映射到列表吗?我真的不确定如何写这个,我知道这可能是一个非常愚蠢的问题,但我刚开始学习Haskell,我想继续前进。
I really don't understand how to do this, and I've been searching a lot. I know I'll need to use getLine, but then what? Would I use a function to map that string to a list? I'm really not sure how I would write this, and I know it's probably a really stupid question, but I just started learning Haskell and I want to go forward.
推荐答案
在这么多行......
In so many lines...
getNumbers :: String -> [Int]
getNumbers str = -- left as exercise
-- helpful functions: `read`, `words`
main :: IO ()
main = do
contents <- readFile "numbers.txt"
let numbers = getNumbers contents
print numbers
这篇关于Haskell - 将包含数字的文件读入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!