In this tutorial I’ve found the following snippet:
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
I can’t figure out how the >>= function is supposed to work. At first it takes a Maybe a value as its first parameter: deposit 100 account >>=
Afterwards, however it seems to take a -> Maybe a as its first parameter: withdraw 200 >>= How could this be approved by the compiler? Shouldn’t >>= always take Maybe a as its first parameter?
A possible solution would be if the >>= function’s precedence would work in the following way: ((a >>= b) >>= c) >>= d
But as far as I know, it is the opposite: a >>= (b >>= (c >>= d))
nope.
infixlmeans that it’s left-associative, soa >>= b >>= c >>= d ≡ ((a >>= b) >>= c) >>= d.It wouldn’t actually make much sense if it were
infixr, would it?>>=always returns a monad, and its RHS takes a function. So in any chain of monadic expressions linked with>>=would be in the(->) rmonad, which is hardly the most useful one.