Why is f <$> g <$> x equivalent to (f . g) <$> x although <$> is not right-associative?

吃可爱长大的小学妹 提交于 2019-12-23 07:03:12

问题


Why is f <$> g <$> x equivalent to (f . g) <$> x although <$> is not right-associative?

(This kind of equivalence is valid in a popular idiom with plain $, but currently $ is right-associative!)

<*> has the same associativity and precedence as <$>, but behaves differently!

Example:

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> 

From the definition of <$>, I would expect show <$> show <$> Just 3 to fail, too.


回答1:


Why is f <$> g <$> x equivalent to (f . g) <$> x?

This isn't so much a functor-thing as a Haskell-thing. The reason it works is that functions are functors. Both <$> operators work in different functors!

f <$> g is in fact the same as f . g, so the equivalence you're asking about is rather more trivial than f <$> (g <$> x) ≡ f . g <$> x.



来源:https://stackoverflow.com/questions/30911093/why-is-f-g-x-equivalent-to-f-g-x-although-is-not-right-assoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!