haskell - few more monad - Reader Monad

we have seen before the (->) r is an instance of functor, and we can do things like this : 

this basically allow us to do the fmap function mapping. 

ghci> let f = (*5)  
ghci> let g = (+3)  
ghci> (fmap f g) 8  
55  

 we have seen also the applicative functors, the allow to combine functions calls. 

ghci> let f = (+) <$> (*2) <*> (+10)  
ghci> f 3  
19  

 

but what if we want to do this in the do monad? we can import the "control.Monad.Instances" which hasd efined the Monad instance fore ((->) r)

instance Monad ((->) r) where  
    return x = \_ -> x  
    h >>= f = \w -> f (h w) w  

 the "retrurn " is the equivalent of "pure" method, it takes a value adn puts that in the minimal context that always has the value as its results.

 

now, as an alternative way of doing the >>= combination,we  can use the do monad as such .

 

import Control.Monad.Instances  
  
addStuff :: Int -> Int  
addStuff = do  
    a <- (*2)  
    b <- (+10)  
    return (a+b)  

 

call this method:

ghci> addStuff 3  
19  

 

 Both (*2) and (+10) get applied to the number 3 in this case. return (a+b) does as well, but it ignores it and always presents a+b as the result. For this reason, the function monad is also called the reader monad. All the functions read from a common source.

 

we can do this to illustrate the idea as the following.

addStuff :: Int -> Int  
addStuff x = let  
    a = (*2) x  
    b = (+10) x  
    in a+b  

 

 

你可能感兴趣的:(haskell)