我簡化了所討論的功能。我在建立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