[英]Why is f <$> g <$> x equivalent to (f . g) <$> x although <$> is not right-associative?
为什么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>
根据<$>
的定义,我希望show <$> show <$> Just 3
也会失败。
为什么
f <$> g <$> x
等价于(f . g) <$> x
?
这不是一个像Haskell那样的仿函数。 它起作用的原因是函数是函子。 两个<$>
运算符都在不同的函子中工作!
f <$> g
实际上与 f . g
相同 f . g
f . g
,所以你要问的等价比f <$> (g <$> x) ≡ f . g <$> x
更微不足道f <$> (g <$> x) ≡ f . g <$> x
f <$> (g <$> x) ≡ f . g <$> x
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.