fmap与bind的关系
Relationship between fmap and bind
查阅 Control.Monad
文档后,我对
这段话:
The above laws imply:
fmap f xs = xs >>= return . f
他们是怎么暗示的?
As a consequence of these laws, the Functor
instance for f will satisfy
fmap f x = pure f <*> x
Applicative
和Monad
的关系说
pure = return
(<*>) = ap
ap
说
return f `ap` x1 `ap` ... `ap` xn
is equivalent to
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
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
定律,也是得出这个结论的有效途径。
查阅 Control.Monad
文档后,我对
这段话:
The above laws imply:
fmap f xs = xs >>= return . f
他们是怎么暗示的?
As a consequence of these laws, the
Functor
instance for f will satisfyfmap f x = pure f <*> x
Applicative
和Monad
的关系说
pure = return
(<*>) = ap
ap
说
return f `ap` x1 `ap` ... `ap` xn
is equivalent to
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
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
定律,也是得出这个结论的有效途径。