[Haskell-beginners] question on types

Jake Penton djp at arqux.com
Fri Jul 29 01:42:22 CEST 2011


Yikes.

I have been doing a fair bit of productive programming in Haskell, thinking that I am making a bit of progress. Then I hit something that is apparently *really simple* that I do not understand at all. How discouraging.

Here is the code that makes me realize I don't understand types or type inference very well at all yet:

f :: a
f = 1

When I try to load the above, ghci gives me:

    No instance for (Num a)
      arising from the literal `2'
    In the expression: 2
    In an equation for `f': f = 2
Failed, modules loaded: none.


Ok, so then I try:

g:: (Num a) => a
g = 2

This compiles.

Why? I mean, why is the first example (defining f) wrong, but the second example (defining g) ok?

A slight variation on this is:

h:: a
h = 'a'

to which ghci replies:

    Couldn't match type `a' with `Char'
      `a' is a rigid type variable bound by
          the type signature for c :: a
          at /Users/David/Project/EoP/ch04/weak.hs:114:1
    In the expression: 'a'
    In an equation for `c': c = 'a'

This last example is probably the most basic one which I need to understand. But, why is the problem apparently a different one than in the definition of "f" above?

Of course, I cannot think of a reason to actually define things as shown above under ordinary circumstances. The code above is just boiled down to the simplest case I could find to illustrate my confusion.

I guess I interpret "f::a" to mean "f is some (any) type a". So why can't it be whatever "1" is, which I suppose is Integer. What is the type system looking for? And why does the constraint (Num a) make things ok?

Please point me in the direction of any reading I should do to clear up my confusion.

TIA.

- Jake -
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110728/d96c1840/attachment.htm>


More information about the Beginners mailing list