fmap和bind之间的关系

时间:2017-05-22 05:52:18

标签: haskell monads functor

在查看Control.Monad文档后,我感到很困惑 这段话:

  

上述法律意味着:

     

fmap f xs = xs >>= return . f

他们如何暗示?

2 个答案:

答案 0 :(得分:9)

Control.Applicative

  

作为这些法律的结果,f的Functor实例将满足

fmap f x = pure f <*> x

ApplicativeMonad之间的关系表示

pure = return
     
(<*>) = ap

ap

return f `ap` x1 `ap` ... `ap` xn
     

相当于

liftMn f x1 x2 ... xn

因此

fmap f x = pure f <*> x
         = return f `ap` x
         = liftM f x
         = do { v <- x; return (f v) }
         = x >>= return . f

答案 1 :(得分:6)

Functor instances are unique,从某种意义上说,如果FFunctor并且你有一个foobar :: (a -> b) -> F a -> F b函数,那么foobar id = id(也就是说,它跟随着foobar = fmap第一个仿函法)然后liftM :: Monad f => (a -> b) -> f a -> f b liftM f xs = xs >>= return . f 。现在,考虑这个功能:

liftM id xs

那么liftM id xs xs >>= return . id -- id does nothing, so... xs >>= return -- By the second monad law... xs 是什么?

liftM id xs = xs

liftM id = id;也就是liftM = fmap。因此,fmap f xs = xs >>= return . f ;或者,换句话说......

Applicative
通过{{1}}法律路由的

epheriment's answer也是达成此结论的有效方式。