【问题标题】:Why is f <$> g <$> x equivalent to (f . g) <$> x although <$> is not right-associative?为什么 f <$> g <$> x 等价于 (f . g) <$> x 虽然 <$> 不是右结合的?
【发布时间】:2015-06-18 09:09:20
【问题描述】:

为什么f &lt;$&gt; g &lt;$&gt; x 等同于(f . g) &lt;$&gt; x 虽然&lt;$&gt; 不是右关联的?

(这种等价在a popular idiom 和普通$ 中有效,但目前$ 是右结合的!)

&lt;*&gt;&lt;$&gt; 具有相同的关联性和优先级,但行为不同!

例子:

Prelude Control.Applicative> (show . show) <$> Just 3
Just "\"3\""
Prelude Control.Applicative> show <$> show <$> Just 3
Just "\"3\""
Prelude Control.Applicative> pure show <*> pure show <*> Just 3

<interactive>:12:6:
    Couldn't match type `[Char]' with `a0 -> b0'
    Expected type: (a1 -> String) -> a0 -> b0
      Actual type: (a1 -> String) -> String
    In the first argument of `pure', namely `show'
    In the first argument of `(<*>)', namely `pure show'
    In the first argument of `(<*>)', namely `pure show <*> pure show'
Prelude Control.Applicative> 
Prelude Control.Applicative> :i (<$>)
(<$>) :: Functor f => (a -> b) -> f a -> f b
    -- Defined in `Data.Functor'
infixl 4 <$>
Prelude Control.Applicative> :i (<*>)
class Functor f => Applicative f where
  ...
  (<*>) :: f (a -> b) -> f a -> f b
  ...
    -- Defined in `Control.Applicative'
infixl 4 <*>
Prelude Control.Applicative> 

根据&lt;$&gt; 的定义,我预计show &lt;$&gt; show &lt;$&gt; Just 3 也会失败。

【问题讨论】:

    标签: haskell syntax infix-notation applicative infix-operator


    【解决方案1】:

    为什么f &lt;$&gt; g &lt;$&gt; x 等同于(f . g) &lt;$&gt; x

    这与其说是函子的东西,不如说是 Haskell 的东西。它起作用的原因是函数是函子。两个&lt;$&gt; 运算符都在不同的函子中工作!

    f &lt;$&gt; g 实际上与f . g相同,所以你问的等价性比f &lt;$&gt; (g &lt;$&gt; x) ≡ f . g &lt;$&gt; x 更微不足道。

    【讨论】:

    • 感谢您的聪明观察!
    • 嗯,我的意思是把另一个 Functor 实例考虑在内。或许,“观察”不是一个好词。
    • 故事的寓意:() = (.) for the function Functor.
    • 函数函子的(&lt;$&gt;)函数在作为函子的函数之前组合一个函数,其Functor实例具有定义为(.)函数的(&lt;$&gt;)函数,其函数是获取一个函数并生成一个函数,该函数获取一个函数并给出一个函数,该函数的功能类似于两个函数组合在一起。
    • 对神秘类型检查的代码的相同解释(不确定该代码是否另外错误或仍然等同于预期):forever putStrLn "Hello, infinity"
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多