无法将期望类型“Int”与实际类型“IO [Int]”匹配

时间:2014-01-05 22:25:52

标签: haskell types io compiler-errors

有人可以解释我的功能发生了什么。

arrayReader :: [Int] -> IO [Int]
arrayReader arr = do
  item <- readLn
  return $ if item == 0
          then arr
          else arrayReader item:arr

但是Haskell对第6行并不满意:

reader.hs:6:17:
    Couldn't match expected type `Int' with actual type `IO [Int]'
    In the return type of a call of `arrayReader'
    In the first argument of `(:)', namely `arrayReader item'
    In the expression: arrayReader item : arr

有人可以解释需要更改哪些内容才能编译此函数吗?

1 个答案:

答案 0 :(得分:2)

首先,您有一个优先级错误 - arrayReader item:arr解析为(arrayReader item):arr。你需要写arrayReader (item:arr)

其次,arrayReader会生成IO [Int]类型的内容,但在此上下文return采用[Int]类型的内容并生成IO [Int]。您需要重新安排代码,以便仅在return上调用arr,而不是arrayReader的结果。