haskell - few more monad - Reader Monad

本文深入探讨了函数式编程中的Monad概念,包括返回(等价于纯方法)、>>=组合以及如何在Domonad中实现类似操作。通过实例展示了如何使用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  

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值