答案 0 :(得分:9)
作为这些法律的结果,f的
Functor
实例将满足fmap f x = pure f <*> x
Applicative
和Monad
之间的关系表示
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,从某种意义上说,如果F
是Functor
并且你有一个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也是达成此结论的有效方式。