1
votes

I'm a bit confused by this thing in GHCI when you use functions of a specific type class, but not specifying what concrete type you want. Consider the following code:

pure (1+) <*> pure 1
> 2

The way I understand it, when you type something into GHCI, it evaluates the expression and calls putStrLn . show on it. But how can this be evaluated? Why is this 2? I mean, it makes sense and it's probably 2 for most Applicative instances, but there's no way to know for sure, right? If we check the type of the expression we get:

pure (1+) <*> pure 1 :: (Num b, Applicative f) => f b

OK, fair enough, the types look reasonable, but there was never any type class instance specified, so how did GHCI/Haskell know what function to call when I wrote pure/<*>?

Intuition from other languages tell that this should be an error. Kind of like trying to call an instance method statically in an OOP language (obviously not the same, but it's that kind of feeling I'm getting).

What's going on here?

1
It's type defaulting downloads.haskell.org/~ghc/latest/docs/html/users_guide/…. Also f resolved to IO as ghci runs in IO monad.zakyggaps
Thanks! Would you mind posting an answer so I can accept?sara

1 Answers

5
votes

It's due to two features of ghci:

  1. type defaulting, which resolves Num b => b to Integer (notice that 1 is actually fromInteger 1 and you may define -- but not recommanded -- some numeric data type in which fromInteger 1 + fromInteger 1 == k and show k == "3", so this matters):
  2. the whole ghci runs in IO monad, and if an expression can be instantiated to an IO action, then it will be, so Applicative f => f is resolved to IO. If the expression is of type C1 f => f a, and IO isn't an instance of that type class C1, ghci will raise an ambiguity error.