What type is chosen for a polymorphic expression when printed? - haskell

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.

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)

Understanding how the pure function is resolved in 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.

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.

Haskell Return Doesn't Match Expected

Could someone tell me why the following code doesn't work?
test :: String
test =
do
return ("Hi")
I've been struggling to make the do statement work for a while now, and I've chased it down to this problem. I know this isn't how you ought to make a constant, but this neatly sums up the problem I've been getting.
I get the following error:
Test.hs:5:21:
Couldn't match expected type `Char' with actual type `[Char]'
In the first argument of `return', namely `("Hi")'
In a stmt of a 'do' block: return ("Hi")
In the expression: do { return ("2") }
Update: Ah I see. In my effort to abstract down to the part that was causing me the problem I just created another one. Despite that, this did inadvertently cause me to solve the problem anyway.
GHCi gives the following:
:t do {return ("Hi")}
do {return ("Hi")} :: Monad m => m [Char]
Which means do {return ("Hi")} is not of type String a.k.a. [Char], but of Monad m => m [Char].
A list is a monad, so it takes care of the Monad m in the type but leaves [Char]; but after the list is taken away from the String, what's left is just Char, which cannot match the [Char], so the error results.
return in Haskell is not a keyword--it's just a normal function which happens to have that name. In functions, the expression is returned automatically:
test :: String
test = "Hi"
This is true even if your function take an argument:
double x = 2 * x
It seems you're really new to Haskell. You should read a nice book like "Learn You a Haskell" to get acquainted with it because it is literally nothing like any other language you've ever used, so your existing experience won't be very helpful.
To define a constant value (within a module) you just need
test :: String
test = "Hi"
But I guess that you are trying to do IO.
Please, Learn you a Haskell for the Great Good!

Converting IO Int to Int

I've created a combobox from converting a xmlWidget to a comboBox with the function castTocomboBox and now I want to get the text or the index of the active item. The problem is that if I use the comboBoxGetActive function it returns an IO Int result and I need to know how can I obtain the Int value. I tried to read about monads so I could understand what one could do in a situation like this but I don't seem to understand. I appreciate all the help I can get. I should probably mention that I use Glade and gtk2hs.
As a general rule you write something like this:
do
x <- somethingThatReturnsIO
somethingElseThatReturnsIO $ pureFunction x
There is no way to get the "Int" out of an "IO Int", except to do something else in the IO Monad.
In monad terms, the above code desugars into
somethingThatReturnsIO >>= (\x -> somethingElseThatReturnsIO $ pureFunction x)
The ">>=" operator (pronounced "bind") does the magic of converting the "IO Int" into an "Int", but it refuses to give that Int straight to you. It will only pass that value into another function as an argument, and that function must return another value in "IO". Meditate on the type of bind for the IO monad for a few minutes, and you may be enlightened:
>>= :: IO a -> (a -> IO b) -> IO b
The first argument is your initial "IO Int" value that "comboBoxGetActive" is returning. The second is a function that takes the Int value and turns it into some other IO value. Thus you can process the Int, but the results of doing so never escape from the IO monad.
(Of course there is the infamous "unsafePerformIO", but at your level of knowledge you may be certain that if you use it then you are doing it wrong.)
(Actually the desugaring is rather more complicated to allow for failed pattern matches. But you can pretend what I wrote is true)
Well, there is unsafePerformIO: http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/System-IO-Unsafe.html#v:unsafePerformIO
(If you want to know how to find this method: Go to http://www.haskell.org/hoogle and search for the signature you need, here IO a -> a)
That said, you probably heard of "What happens in IO stays in IO". And there are very good reasons for this (just read the documentation of unsafePerformIO). So you very likely have a design problem, but in order to get help from experienced Haskellers (I'm certainly not), you need to describe your problem more detailed.
To understand what those types are –step by step–, first look up what Maybe and List are:
data Maybe a = Nothing | Just a
data [a] = [] | a : [a]
(Maybe a) is a different type than (a), like (Maybe Int) differs from (Int).
Example values of the type (Maybe Int) are
Just 5 and Nothing.
A List of (a)s can be written as ([ ] a) and as ([a]). Example values of ([Int]) are [1,7,42] and [ ].
Now, an (IO a) is a different thing than (a), too: It is an Input/Output-computation that calculates a value of type (a). In other words: it is a script or program, which has to be executed to generate a value of type (a).
An Example of (IO String) is getLine, which reads a line of text from standard-input.
Now, the type of comboBoxGetActive is:
comboBoxGetActive :: ComboBoxClass self => self -> IO Int
That means, that comboBoxGetActive is a function (->) that maps from any type that has an instance of the type-class ComboBoxClass (primitive type-classes are somehow similar to java-interfaces) to an (IO Int). Each time, this function (->) is evaluated with the same input value of this type (self) (whatever that type is), it results in the same value: It is always the same value of type (IO Int), that means that it is always the same script. But when you execute that same script at different times, it could produce different values of type (Int).
The main function of your program has the type (IO ()), that means that the compiler and the runtime system evaluate the equations that you program in this functional language to the value of main, which will be executed as soon as you start the program.

Resources