Understanding how the pure function is resolved in Haskell - haskell

In GHCi when I type pure 2 it returns 2; or pure "aa" returns "aa". I wonder how this applicative instance is resolved for 2 or "aa" by GHCi.

GHCi performs some magic to be user-friendly.
When entering an expression whose type is of the form ... => f a, it tries to instantiate f to IO. In your case, this is possible since IO is an applicative (and a monad).
Secondly, when an expression having a type of the form ... => IO a is entered, it is run as an IO action.
Finally, if a is of class Show, the result is printed. In your case "aa" is the result (and the type a is String), so GHCi prints that.

Related

What is the default type evaluation of MonadPlus in Haskell?

I have the following code:
import Control.Monad
coin :: MonadPlus m => m Int
coin = return 0 `mplus` return 1
If I evaluate coin :: Maybe Int on the interpreter, it prits Just 0. That's normal because of the implementation of Maybe as instance of MonadPlus.
If I evaluate coin :: [Int]on the interpreter, it prints [0, 1], because the implementation of mplus on list is an append.
But if I evaluate coin, without any type decorators, it prints 0. Why? What type does the interpreter 'converts' coin to evaluate it?
This code is extracted from: http://homes.sice.indiana.edu/ccshan/rational/S0956796811000189a.pdf
Yeah, this is a not super-well documented corner of ghci. When you enter an expression into ghci, it uses the expression's type to decide what to do:
IO (): Run the action, do nothing further.
Show a => IO a: Run the action and print the result.
any other IO a: Run the action, do nothing further.
anything else: wrap the whole expression with print.
How does it decide which of these types a thing has? Easy: it tries to unify the type of your expression which each of the above signatures in turn and solve all resulting constraints. (For the cognoscenti: this is in addition to the extended defaulting rules! This explains why it appears to be defaulting the m, even though neither the standard defaulting rules nor the extended defaulting rules say what default to use.)
So, since your expression does not unify with IO () but does unify with Show a => IO a, ghci finds m ~ IO (and a ~ Int) during unification, discovers that there is a MonadPlus IO (and a Show Int) instance to resolve the constraints, runs your action, and prints the result.
GHCi (but not GHC in general) will, in the absence of a signature specifying otherwise, specialise polymorphic type constructors to IO whenever possible. IO actions at the prompt, in turn, are executed and have their results monadically bound to the it variable, which is then printed (i.e. do { it <- action; print it }) as long as there is a Show instance for the result type (cf. Daniel Wagner's answer). For more details, have a look at the I/O actions at the prompt and The it variable sections of the User's Guide.
In your specific case, it happens that there is a MonadPlus instance for IO. You get return 0 from it because mplus for IO only executes the second action if the first one throws an exception. One demonstration:
GHCi> readLn `mplus` readLn :: IO Integer
0
0
GHCi> readLn `mplus` readLn :: IO Integer
foo
1
1
GHCi> readLn `mplus` readLn :: IO Integer
foo
bar
*** Exception: user error (Prelude.readIO: no parse)

How does GHCi pick an instance of the Monad type class to use for polymorphic actions?

I'm new to Haskell so this might be a noob question.
When I do return 10 >>= return GHCi shows 10. When I check the type of return 10 with :t it just says return 10 :: (Monad m, Num a) => m a, and of I do typeOf return 10 I get an error.
But as far as I understand, Haskell must have used a particular instance of >>= to evaluate return 10 >>= return, so which instance did it use and how did it decide which one to use?
This follows the idea that GHCi is sort of like a giant do block of IO. Whenever you type in something that is an expression it first tries to see if the type of the result can be specialized to something of the form IO a. If it can, it executes the IO action and just prints the result. Only otherwise does it print the result of the expression itself.
To force GHCi to go to whatever specific monad you want, you can add a type annotation. Notice how IO gets treated differently (and the same way as the expression would have been treated without any annotation).
ghci> return 10 >>= return :: Maybe Int
Just 10
ghci> return 10 >>= return :: [Int]
[10]
ghci> return 10 >>= return :: IO Int
10
As an aside, there is an entirely different problem regarding what instance of Num is chosen, and that one has everything to do with defaulting rules and the monomorphism restriction.

Calling show on results from generic functions in ghci

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?
It's due to two features of ghci:
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):
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.

How does GHCi print partially-applied values created from "pure"?

I've been playing around with Applicative instances in order to figure out how they work. However, I honestly don't understand this behavior.
If I define my own datatype, then apply pure to it with no other arguments, nothing prints out, but it errors if I try to apply something to the result.
ghci> data T = A
ghci> pure A
ghci> pure A 0
<interactive>:21:1:
No instance for (Show T) arising from a use of ‘print’
In a stmt of an interactive GHCi command: print it
However, if I make T an instance of Show, then A is printed out in both cases.
ghci> data T = A deriving (Show)
ghci> pure A
A
ghci> pure A 0
A
What I really don't understand is how pure A can be a value that is printed differently between the two cases. Isn't pure A partially applied?
I do understand why calling pure A 0 errors in the first example and doesn't in the second—that makes sense to me. That's using the ((->) r) instance of Applicative, so it simply yields a function that always returns A.
But how is pure instantiated with only one value when the type of the applicative itself isn't yet known? Furthermore, how can GHC possibly print this value?
GHCi is a little bit peculiar. In particular, when you type an expression at the prompt, it tries to interpret it in two different ways, in order:
As an IO action to execute.
As a value to print out.
Since IO is Applicative, it is interpreting pure A as an IO action producing something of type T. It executes that action (which does nothing), and since the result is not in Show, it does not print anything out. If you make T an instance of Show, then it kindly prints out the result for you.
When you write pure A 0, GHCi sees this:
pure :: Applicative f => a -> f a
pure A :: Applicative f => f T
And since you apply pure A to 0, pure A must be a function a->b for some types a and b, and a must contain 0.
(Num a, Applicative f) => f T ~ (a -> b)
(Note that x ~ y means that x and y unify—they can be made to have the same type.)
Thus we must have f ~ ((->) a) and T ~ b, so in fact GHC infers that, in this context,
pure A :: Num a => ((->) a) T
Which we can rewrite as
pure A :: Num a => a -> T
Well, (->) a is an instance of Applicative, namely "reader", so this is okay. When we apply pure A to 0 we get something of type T, namely A. This cannot be interpreted as an IO action, of course, so if T is not an instance of Show, GHCi will complain.
When you give a value of ambiguous type to the GHCi prompt to evaluate, it tries to default the type in various ways. In particular, it tries whether it can fit an IO a type, in case you want to execute an IO action (see the GHC manual). In your case, pure A defaults to the type IO T. Also:
Furthermore, GHCi will print the result of the I/O action if (and only if):
The result type is an instance of Show.
The result type is not ().

What type is chosen for a polymorphic expression when printed?

What is the type of return "abc" when printed in ghci?
The point of the question is that it's polymorphic in the monad:
ghci> :t return "abc"
return "abc" :: (Monad m) => m [Char]
and what gets printed depends on which monad is chosen:
ghci> return "abc" :: Maybe String
Just "abc"
ghci> return "abc" :: [] String
["abc"]
but here's what's actually printed:
ghci> return "abc"
"abc"
When you type an expression expr into GHCi, the following things happen:
The expression is type-checked. If there is an error, GHCi tells you the error and gives up.
Otherwise, say expr is found to have type t; GHC tries to match t against IO a.
If it succeeds, then it executes something like it <- expr, then if a is an instance of Show and is not (), it executes print it.
If it fails, and t itself is an instance of Show, GHCi does something like let it = expr and then print it.
Otherwise, it complains.
Essentially, you need a way at the GHCi prompt both of running IO actions and getting at the values they return, and of playing around with pure values and seeing what you get. That's why GHCi behaves the way it does: if it seems like you're using an IO action, GHCi will do it, and then if that action has a result that can be shown and is interesting (i.e. not ()) then it shows the result to you. If it can't show the result to you, then it's no big deal, because you probably just wanted to run the IO action anyway; if you wanted the result you would have named it with <-. On the other hand, if it seems like your expression is not an IO action, GHCi calculates it and shows it to you, and if it can't be shown then GHCi can't do anything useful (no side-effects this time), so complains.
In this case, return "abc" typechecks as IO String, and String is an instance of Show, so GHCi does something like
it <- return "abc"
print it
which by the monad laws is exactly the same as just doing
print "abc"
hence the result.
Haskell has a slightly baffling set of rules for deciding the types of expressions involving numbers; you can see the Report section on ambiguous types and default instances. So the answer to the general question is complicated. But within GHCi, if you enter an expression e, you can rely on these rules to apply:
If the expression e can be typed as IO T for some type T, and if T has a Show instance, GHCi will run the computation and print the resulting value of type T. That's what's happening in your third example.
If the expression e *cannot* be typed in the IO monad, then the default-instance rules come into play, and GHCi will choose a type according to those rules. If the type has a Show instance GHCi will then print show e. That's what happens in your first two examples: Maybe String and [String] are pure values with Show instances.
If e's type does not have a Show instance, then GHCi will complain. That will happen if you type an expression like flip take.

Resources