Haskell 中关于 <$> 和 <*> 的优先级混淆
Precedence Confusion about <$> and <*> in Haskell
两个示例均来自 http://learnyouahaskell.com/functors-applicative-functors-and-monoids#applicative-functors、
1). (+) <$> (+3) <*> (*100) $ 5
(+) <$> (+3) <*> (*100) $ 5, the 5 first got applied to (+3) and
(*100), resulting in 8 and 500. Then, + gets called with 8 and 500,
resulting in 508.
从第一个例子来看,似乎 <*>
的优先级高于 <$>
。
2). (++) <$> Just "johntra" <*> Just "volta"
(++) <$> Just "johntra" <*> Just "volta", resulting in a value
that's the same as Just ("johntra"++),and now Just ("johntra"++) <*>
Just "volta" happens, resulting in Just "johntravolta".
从第二个例子来看,似乎 <$>
的优先级高于 <*>
。
那么它们的优先级相同吗?谁能给我一些 explanations/references?
<$>
和 <*>
具有相同的优先级和左结合性。 $
的最低优先级为零。您可以使用 ghci
浏览有关它们的信息:
λ> :i (<$>)
(<$>) :: Functor f => (a -> b) -> f a -> f b
-- Defined in ‘Data.Functor’
infixl 4 <$>
λ> :i (<*>)
class Functor f => Applicative (f :: * -> *) where
...
(<*>) :: f (a -> b) -> f a -> f b
...
-- Defined in ‘Control.Applicative’
infixl 4 <*>
现在您可以算出类型,看看它们是如何进行类型检查的。
实际上它们都具有相同的优先级(infixl 4
:(<*>)
and (<$>)
),您可以从左到右阅读它 -
(+) <$> (+3) <*> (*100) $ 5
= ((+) <$> (+3)) <*> (*100) $ 5
= (\ a b -> (a+3) + b) <*> (\ a -> a*100) $ 5
= (\ a -> (a+3) + (a*100)) $ 5
= 8 + 500 = 508
记住 在这种情况下我们有 f <*> g = \x -> f x (g x)
两个示例均来自 http://learnyouahaskell.com/functors-applicative-functors-and-monoids#applicative-functors、
1). (+) <$> (+3) <*> (*100) $ 5
(+) <$> (+3) <*> (*100) $ 5, the 5 first got applied to (+3) and
(*100), resulting in 8 and 500. Then, + gets called with 8 and 500,
resulting in 508.
从第一个例子来看,似乎 <*>
的优先级高于 <$>
。
2). (++) <$> Just "johntra" <*> Just "volta"
(++) <$> Just "johntra" <*> Just "volta", resulting in a value
that's the same as Just ("johntra"++),and now Just ("johntra"++) <*>
Just "volta" happens, resulting in Just "johntravolta".
从第二个例子来看,似乎 <$>
的优先级高于 <*>
。
那么它们的优先级相同吗?谁能给我一些 explanations/references?
<$>
和 <*>
具有相同的优先级和左结合性。 $
的最低优先级为零。您可以使用 ghci
浏览有关它们的信息:
λ> :i (<$>)
(<$>) :: Functor f => (a -> b) -> f a -> f b
-- Defined in ‘Data.Functor’
infixl 4 <$>
λ> :i (<*>)
class Functor f => Applicative (f :: * -> *) where
...
(<*>) :: f (a -> b) -> f a -> f b
...
-- Defined in ‘Control.Applicative’
infixl 4 <*>
现在您可以算出类型,看看它们是如何进行类型检查的。
实际上它们都具有相同的优先级(infixl 4
:(<*>)
and (<$>)
),您可以从左到右阅读它 -
(+) <$> (+3) <*> (*100) $ 5
= ((+) <$> (+3)) <*> (*100) $ 5
= (\ a b -> (a+3) + b) <*> (\ a -> a*100) $ 5
= (\ a -> (a+3) + (a*100)) $ 5
= 8 + 500 = 508
记住 在这种情况下我们有 f <*> g = \x -> f x (g x)