[英]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.