简体   繁体   English

Haskell中关于<$>和<*>的优先混淆

[英]Precedence Confusion about <$> and <*> in Haskell

Two examples both from http://learnyouahaskell.com/functors-applicative-functors-and-monoids#applicative-functors , 来自http://learnyouahaskell.com/functors-applicative-functors-and-monoids#applicative-functors的两个示例,

1). 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.

From the first example, it seems like <*> has higher precedence than <$> . 从第一个示例来看, <*>优先级似乎比<$>优先级高。

2). 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".

From the second example, it seems like <$> has higher precedence than <*> . 从第二个示例来看, <$>优先级似乎比<*>优先级高。

So do they have the same precedence? 那么它们具有相同的优先级吗? can someone give me some explanations/references? 有人可以给我一些解释/参考吗?

indeed they both have the same precedence ( infixl 4 : (<*>) and (<$>) ) and you can just read it from left to right - 实际上,它们都具有相同的优先级( infixl 4(<*>)(<$>) ),您可以从左到右读取它-

(+) <$> (+3) <*> (*100) $ 5
= ((+) <$> (+3)) <*> (*100) $ 5
= (\ a b -> (a+3) + b) <*> (\ a -> a*100) $ 5
= (\ a -> (a+3) + (a*100)) $ 5
= 8 + 500 = 508

remember in this case we have f <*> g = \\x -> fx (gx) 请记住,在这种情况下,我们有f <*> g = \\x -> fx (gx)

<$> and <*> has same precedence and left associativity. <$><*>具有相同的优先级,并且具有左关联性。 $ has the lowest precedence of zero. $的最低优先级为零。 You can use ghci to explore information about them: 您可以使用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 <*>

Now you can work out the types to see how they typecheck. 现在,您可以算出类型,以查看它们的类型检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM