【问题标题】:Relationship between fmap and bindfmap和bind的关系
【发布时间】:2017-05-22 05:52:18
【问题描述】:

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

上述法律暗示:

fmap f xs = xs >>= return . f

他们是如何暗示的?

【问题讨论】:

    标签: haskell monads functor


    【解决方案1】:

    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
    

    【讨论】:

    • 嗯,这只是将问题推到Applicative 级别。那就是:为什么fmap f x = pure f &lt;*&gt; xApplicative 法律的结果?毕竟,他们甚至没有提到fmap!然后要回答这个问题,您需要@duplode 对参数性的观察...
    【解决方案2】:

    Functor instances are unique,在某种意义上,如果FFunctor,并且你有一个函数foobar :: (a -&gt; b) -&gt; F a -&gt; 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 法则,也是得出此结论的有效方法。

    【讨论】:

    • 我认为我的回答中的替换更直接,但你的回答更多地表达了为什么它应该的直觉。
    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多