Perhaps the monad binds the function

In this tutorial, I 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 understand how the >>= function should work. First, the first parameter is Maybe a : deposit 100 account >>=

Subsequently, however, as the first parameter, it takes a -> Maybe a : withdraw 200 >>= How can this be approved by the compiler? Should >>= always accept Maybe a as its first parameter?

A possible solution may be if the priority of the function >>= will work as follows: ((a >>= b) >>= c) >>= d

But as far as I know, this is the opposite: a >>= (b >>= (c >>= d))

+6
source share
1 answer

as far as I know, this is the opposite: a >>= (b >>= (c >>= d))

No.

 GHCi> :i >>= class Monad m where (>>=) :: ma -> (a -> mb) -> mb ... -- Defined in `GHC.Base' infixl 1 >>= 

infixl means that it is left-associative, therefore a >>= b >>= c >>= d ≑ ((a >>= b) >>= c) >>= d .

It really wouldn't make sense if it were infixr , would it? >>= always returns the monad, and its RHS performs the function. Thus, any chain of monadic expressions associated with >>= would be in the monad (->) r , which is hardly the most useful.

+14
source

Source: https://habr.com/ru/post/919595/


All Articles