[Haskell-cafe] What is an "expected type" ...

Joe Fredette jfredett at gmail.com
Sun Jun 28 11:29:10 EDT 2009

When Haskell runs it's type checker, it tries to "guess" the type of 
each function. Thats why you can write:

    map (+1)

and it knows that you're talking about a function of type:

    Num a => [a] -> [a]

Another thing, called 'defaulting' resolves this, but you didn't ask 
about that, so I won't go into it.

An expected type is one that you provide to the compiler in the form of 
a type signature, this can be used to specialize a general type (like 
the one I showed) or
to resolve ambiguous types the compiler can't, or just for 
documentation/good practice. So when I write:

    foo :: Num a => [a] -> [a]
    foo ls = map (+1) ls

The "expected type" for `foo` is `Num a => [a] -> [a]`. I imagine you're 
asking this because you got an error which said your expected type 
doesn't match your inferred type. That might, for instance, happen if I 

    bar :: String
    bar = 'a'

'a' has type `Char`, since `String` is not `Char`, the type checker 
infers that 'a' has type char, but _expects_ it to be type String. Two 
solutions are as follows:

    --- Method 1
    bar :: Char
    bar = 'a'
    --- Method 2
    bar :: String
    bar = "a"
Can you see why those two changes fix the problem?

Also, just as a matter of process, I forwarded this to the 
haskell-beginners list, as I imagine type errors like these come up a 
lot, and someone probably has a better explanation over there.


michael rice wrote:
> as opposed to an "inferred type"?
> Michael
> ------------------------------------------------------------------------
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
A non-text attachment was scrubbed...
Name: jfredett.vcf
Type: text/x-vcard
Size: 296 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20090628/b0eeda45/jfredett.vcf

More information about the Haskell-Cafe mailing list