This question arose while reading the new chapter in the excellent Learn You a Haskell about applicative functors.
The Applicative typeclass has, as part of the definition for the Maybe instance:
pure = Just
If I just go to GHCi and import Control.Applicative, and do:
pure (3+)
I don’t get Just anything (makes sense). But if I use it in part of the expression:
pure (3+) <*> Just 4
I get Just 7. I guess it also isn’t surprising, but I’m missing something integral about how typeclasses work, I think, that there is no ambiguity with the call to pure here.
If my confusion makes sense, can anyone explain what’s going on in detail?
It’s just type inference. The
(<*>)operator requires both arguments to use the sameApplicativeinstance. The right side is aMaybe, so the left side has to be aMaybealso. So that’s how it figures out which instance is used here. You can look at the type of any expression in the interpreter by typing:t expression, and maybe if you just go through each subexpression and look at the type that was inferred, you will get a better picture of what’s going on.