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

被折叠的 条评论
为什么被折叠?



