为什么f< $> g< $> x相当于(f.g)< $> x虽然< $>是不是正确联想?

时间:2015-06-18 09:09:21

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

为什么f <$> g <$> x(f . g) <$> x相当,虽然<$>不是正确关联的?

(这种等效在a popular idiom中与普通$有效,但目前$是正确关联的!)

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

示例:

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也会失败。

1 个答案:

答案 0 :(得分:21)

  

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

这不像Haskell那样是一个有趣的东西。它起作用的原因是函数是函子。 <$>个运算符都适用于不同的函子!

f <$> g实际上与f . g 相同,因此您提出的等效性比f <$> (g <$> x) ≡ f . g <$> x更为微不足道。

相关问题