【发布时间】:2017-05-22 05:52:18
【问题描述】:
【问题讨论】:
【问题讨论】:
由于这些规律,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
【讨论】:
Applicative 级别。那就是:为什么fmap f x = pure f <*> x 是Applicative 法律的结果?毕竟,他们甚至没有提到fmap!然后要回答这个问题,您需要@duplode 对参数性的观察...
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
epheriment's answer,通过Applicative 法则,也是得出此结论的有效方法。
【讨论】: