简体   繁体   中英

Precedence Confusion about <$> and <*> in Haskell

Two examples both from 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.

From the first example, it seems like <*> has higher precedence than <$> .

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 -

(+) <$> (+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)

<$> and <*> has same precedence and left associativity. $ has the lowest precedence of zero. You can use ghci to explore information about them:

λ> :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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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