2015-06-18 21 views
12

为什么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失败了。

回答

21

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

这不像一个Haskell事物那么有趣。它的工作原理是功能是仿函数。两个<$>运营商在不同的功能工作!

f <$> g其实相同f . g,所以你问的是等价的,而不是f <$> (g <$> x) ≡ f . g <$> x更微不足道。

+1

感谢您的智能观察! –

+5

嗯,_you_观察它,不是吗?我只是解析并敲入它... – leftaroundabout

+0

嗯,我的意思是将其他Functor实例考虑进去。也许,“观察”对此并不好。 –

相关问题