为什么f <$> g <$> x等价于(f.g)<$> x虽然<$>不是右关联的?

imz*_*hev 12 syntax haskell infix-notation infix-operator applicative

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

(这种等价在普通的流行习语中是有效的$,但目前$是正确联想的!)

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

例:

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> 
Run Code Online (Sandbox Code Playgroud)

从定义来看<$>,我也希望show <$> show <$> Just 3失败.

lef*_*out 21

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

这不是一个像Haskell那样的仿函数.它起作用的原因是函数是函子.两个<$>操作员都在不同的算子中工作!

f <$> g其实相同f . g,所以你问的是等价的,而不是更多的琐碎f <$> (g <$> x) ? f . g <$> x.

  • 好吧,_you_观察它,不是吗?我只是解析并检查它... (5认同)