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

michael rice nowgate at yahoo.com
Sun Jun 28 12:02:29 EDT 2009


Hey Joe, all,

Got it. Thanks!

An associated question: In programming a local "helper" or "auxilliary" function such as dec2bin' in

dec2bin :: Integer -> [Integer]
dec2bin n = dec2bin' n []
            where dec2bin' n acc
                    | n == 0 = acc
                    | otherwise = let r = rem n 2
                                      m = div (n - r) 2
                                  in dec2bin' m (r : acc)

is there any way to assign a type signature to the helper function?

Michael


--- On Sun, 6/28/09, Joe Fredette <jfredett at gmail.com> wrote:

From: Joe Fredette <jfredett at gmail.com>
Subject: Re: [Haskell-cafe] What is an "expected type" ...
To: "michael rice" <nowgate at yahoo.com>
Cc: "Haskell Cafe mailing list" <haskell-cafe at haskell.org>, beginners at haskell.org
Date: Sunday, June 28, 2009, 11:29 AM

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 wrote:

   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.

/Joe


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 --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090628/28ff14de/attachment.html


More information about the Haskell-Cafe mailing list