[Haskell-cafe] noob question

Daniel Fischer daniel.is.fischer at web.de
Mon Feb 25 19:45:00 EST 2008


To elaborate on what Philippa said, the thing that probably is at the basis of 
your confusion is the fact that integer *literals* are overloaded (actually, 
the literal 3 means "fromInteger 3", where the result type of different 
fromInteger calls in the same expression need not be the same). So if you 
write 3, that can have any type belonging to the Num class, and in

(1/3)^3

the two 3s are instantiated to different types, first, in
(1/3), both literals are defaulted to Double, because by the use of (/), you 
need a type belonging to the Fractional class.
Now (^) has type
(^) :: (Integral b, Num a) => a -> b -> a,
so the second 3 must have a type belonging to the Integral class, that is 
defaulted to Integer.
Thus (1/3)^3 is in fact interpreted as
((1 :: Double) / (3 :: Double)) ^ (3 :: Integer).

In the lambda expression (\k -> (1/k)^k), k is one value, belonging to one 
type t. The occurence of k in (1/k) demands that t belong to Fractional and 
the second occurence of k, ^k, demands that t belong to Integral. None of the 
standard types belongs to both these classes. And in
(\k -> (1/k)^k) 3
fromInteger 3 must have type (Fractional t, Integral t) => t.

HTH,
Daniel

Am Dienstag, 26. Februar 2008 01:01 schrieb Ben:
> I'm just starting to learn Haskell, and I'm having some confusion (I
> think) with how the type inference is working.  Can someone explain
> why, in ghc 6.8.2 this works:
>
> *Main> (1/3)^3
> 3.7037037037037035e-2
>
> But this doesn't
>
> *Main> (\k -> (1/k) ^ k) 3
>
> <interactive>:1:8:
>      Ambiguous type variable `t' in the constraints:
>        `Fractional t' arising from a use of `/' at <interactive>:1:8-10
>        `Integral t' arising from a use of `^' at <interactive>:1:7-15
>      Probable fix: add a type signature that fixes these type
> variable(s)
>
> TIA,
> Ben



More information about the Haskell-Cafe mailing list