我简化了所讨论的功能。我在建立monad内的列表时遇到问题。我怀疑有一个优先问题。我的递归列表构造有什么问题?
newtype Boundary = MkBoundary Integer
testFunc :: [Boundary] -> [Maybe Integer]
testFunc (MkBoundary x:xs)
| (even x) = Just x : testFunc xs
| otherwise = Nothing : testFunc xs
testFunc _ = []
这个按预期工作。但我需要在monad中工作。我将在此示例中使用IO
testFunc :: [Boundary] -> IO [Maybe Integer]
testFunc (MkBoundary x:xs)
| (even x) = return $ Just x : testFunc xs
| otherwise = return $ Nothing : testFunc xs
testFunc _ = []
不管我如何操作优先级,都会中断。
test.hs:6:35:
Couldn't match expected type `[Maybe Integer]'
with actual type `IO [Maybe Integer]'
In the return type of a call of `testFunc'
In the second argument of `(:)', namely `testFunc xs'
In the second argument of `($)', namely `Just x : testFunc xs'
Failed, modules loaded: none.
我想完成的是构建一个列表,然后将其返回给IO。我究竟做错了什么?
他说,他已经简化了问题的功能。有可能他需要在某个地方执行此功能的I/O操作。并且学习如何将纯代码转换为单代码在任何情况下都是非常有用的技巧。 – luqui
噢,但是我也可以看到他是怎么会有一种误解,认为如果他需要在monad中使用它,他需要重写他完美的纯函数,在这种情况下,这个答案是正确的。为清晰起见编辑 – luqui
。 – hugomg