12

为什么f <$> g <$> x等于(f . g) <$> x虽然<$>不是右结合?

(这种等价在带有 plain的流行习语$中是有效的,但目前$是右结合的!)

<*>具有与 相同的关联性和优先级<$>,但行为不同!

例子:

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> 

根据 的定义<$>,我也希望show <$> show <$> Just 3失败。

4

1 回答 1

21

为什么f <$> g <$> x等于(f . g) <$> x

这与其说是函子的事情,不如说是 Haskell 的事情。它起作用的原因是函数是函子。两个<$>运算符都在不同的函子中工作!

f <$> g实际上与 相同f . g因此您要询问的等效性比f <$> (g <$> x) ≡ f . g <$> x.

于 2015-06-18T09:22:10.330 回答