有人可以解释我的功能发生了什么。
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
有人可以解释需要更改哪些内容才能编译此函数吗?
答案 0 :(得分:2)
首先,您有一个优先级错误 - arrayReader item:arr
解析为(arrayReader item):arr
。你需要写arrayReader (item:arr)
。
其次,arrayReader
会生成IO [Int]
类型的内容,但在此上下文return
采用[Int]
类型的内容并生成IO [Int]
。您需要重新安排代码,以便仅在return
上调用arr
,而不是arrayReader
的结果。