你的主要问题是你根本不知道如何操作 monad,所以这里有一些提示:
Monads 有一些函数可以让它们被操纵。这些源于 monad 类型类return和>>=(又名“绑定”)中定义的基本类型。
return允许构造 monad,并>>=首先采用 monad,然后是构造 monad 的函数,并将该函数应用于给定的值。这是您在案例中使用它的方式:
-- Imagine your list to be here:
ioList :: IO [Int]
ioList = return [1,2,3,4,5]
-- If we were to print the second element...
main = ioList >>= ( \a -> return (a !! 1) ) >>= print
-- We could write this in do-notation, syntactic sugar for the above:
main = do
list <- ioList
print (list !! 1)
Run Code Online (Sandbox Code Playgroud)
人们还可以使用该功能liftM从Control.Monad它接受一个功能,它适用于像这样一个单子:
import Control.Monad
main = print (liftM (!! 1) ioList)
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到更多操作 monad 的方法,以及所涉及的各种类型签名的解释,以及 do-notation 和其他内容。