Haskell将整数从文件读取到列表

Haskell将整数从文件读取到列表,haskell,io,Haskell,Io,我有一个简单的文本文件,其中有一行: 6 195 265 750 265 750 196 我有一个功能: executeList :: Integer -> [Integer] -> [String] executeList n x = [reverseAndAdd n i | i <- x] 我得到这个错误: <interactive>:103:15: error: * Couldn't match expected type `[Integer]' with

我有一个简单的文本文件,其中有一行:

6 195 265 750 265 750 196
我有一个功能:

executeList :: Integer -> [Integer] -> [String]
executeList n x = [reverseAndAdd n i | i <- x]
我得到这个错误:

<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

我在互联网上查找如何将IO()转换为[Integer],但没有发现任何有用的东西。也许有人能告诉我怎么做

简而言之,您不能将
IO()
转换为
[整数]

你似乎误解了这个事实。大多数函数都返回一个值。返回类型为
IO a
的函数将返回一个I/O操作,该操作在返回类型为
a
的值之前执行某种排序I/O。在您的例子中,
IO()
是一个I/O操作,它将返回一个空元组。当您编写这样的控制台程序,读取数据,然后打印出一些结果时,您通常会遵循以下模式:

  • 从文件或命令行读取输入
  • 将数据传递给函数进行计算
  • 打印结果

  • 你的整个程序最终将生活在IO monad中
    do
    是一种符号,它是bind操作符的语法糖。这个运算符允许我们将一元计算链接在一起。
    IO字符串
    接受一个
    句柄
    ,并返回一个返回字符串的I/O操作。调用
    内容而不是
    打印列表
    时,是否在主菜单中使用
    打印(executeList 0列表)
    ?请注意,没有(安全)功能
    ioa->a
    。谢谢!!!还有一个问题。是否可以将此列表写入同一函数中的其他文件?我尝试在输入“@motleycrue”上添加:outh但get:parse error之类的内容,而不是手动处理句柄,只需使用
    {read,write}File
    的高级函数即可。对于第二个问题,请考虑<代码>写文件“结果.txt”(unWorkist(0执行列表))<代码>。谢谢大家。祝你们今天愉快,伙计们:)
    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()
    
    main = do
        handle <- openFile "data.txt" ReadMode
        contents <- hGetContents handle
        let singlewords = words contents
            list = f singlewords
            data = executeList 0 list
        print data
        hClose handle   
    
    f :: [String] -> [Integer]
    f = map read