【发布时间】:2017-09-11 01:46:17
【问题描述】:
我有一个包含一行的简单文本文件:
6 195 265 750 265 750 196
我有一个函数:
executeList :: Integer -> [Integer] -> [String]
executeList n x = [reverseAndAdd n i | i <- x]
这需要一个整数,整数列表并返回一个字符串数组。
我想要做的是将该文本文件读取到 [Integer] 列表并将其传递给 executeList 函数。 这是我的代码:
main = do
let list = []
handle <- openFile "data.txt" ReadMode
contents <- hGetContents handle
let singlewords = words contents
list = f singlewords
print list
hClose handle
f :: [String] -> [Integer]
f = map read
我在这里找到了它: Haskell file reading
当我运行“main”时,我得到以下输出: [6,195,265,750,265,750,196]
但是当我尝试像这样将它传递给executeList时:
let list = main
executeList 0 list
我收到此错误:
<interactive>:103:15: error:
* Couldn't match expected type `[Integer]' with actual type `IO ()'
* In the second argument of `executeList', namely `list'
In the expression: executeList 0 list
In an equation for `it': it = executeList 0 list
如果我检查该列表的类型,我会得到:
list :: IO()
我在互联网上查找如何将 IO() 转换为 [Integer] 但没有发现任何有用的信息。也许有人可以告诉我进行这种转换的方法?
【问题讨论】:
-
在你的主目录中使用
print list而不是print (executeList 0 list)?请注意,没有(安全)函数IO a -> a。 -
谢谢!!!还有一个问题。是否可以将此列表写入同一函数中的其他文件?我尝试添加类似:outh
-
但得到:输入“
-
@motleycrue 无需手动处理句柄,只需使用
{read,write}File的高级函数即可。对于您的第二个问题,请考虑writeFile "results.txt" (unwords (executeList 0 list))。 -
谢谢你们。祝你有美好的一天,伙计们:)