Att*_*Kun 6 monads haskell maybe
在本教程中,我发现了以下代码段:
deposit :: (Num a) => a -> a -> Maybe a
deposit value account = Just (account + value)
withdraw :: (Num a,Ord a) => a -> a -> Maybe a
withdraw value account = if (account < value)
then Nothing
else Just (account - value)
eligible :: (Num a, Ord a) => a -> Maybe Bool
eligible account =
deposit 100 account >>=
withdraw 200 >>=
deposit 100 >>=
withdraw 300 >>=
deposit 1000 >>
return True
main = do
print $ eligible 300 -- Just True
print $ eligible 299 -- Nothing
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚>>=函数应该如何工作.首先,它将一个Maybe a值作为其第一个参数:deposit 100 account >>=
然后,它似乎将a -> Maybe a其作为第一个参数:withdraw 200 >>=如何通过编译器批准?不应该>>=总是把Maybe a它作为第一个参数?
一个可能的解决方案是,如果>>=函数的优先级可以按以下方式工作:((a >>= b) >>= c) >>= d
但据我所知,情况正好相反: a >>= (b >>= (c >>= d))
lef*_*out 14
据我所知,情况正好相反:
a >>= (b >>= (c >>= d))
不.
GHCi> :i >>=
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
...
-- Defined in `GHC.Base'
infixl 1 >>=
Run Code Online (Sandbox Code Playgroud)
infixl意味着它是左关联的,所以a >>= b >>= c >>= d ? ((a >>= b) >>= c) >>= d.
它实际上没有多大意义,是infixr吗?>>=总是返回一个monad,它的RHS采用一个函数.所以在与monad 相关的任何 monadic表达链中>>=都会出现(->) rmonad,这几乎不是最有用的.