[Haskell-beginners] Re: question about styles of recursion
Brent Yorgey
byorgey at seas.upenn.edu
Fri Mar 27 08:42:56 EDT 2009
On Fri, Mar 27, 2009 at 09:12:46AM +0000, 7stud wrote:
> Daniel Fischer <daniel.is.fischer <at> web.de> writes:
> >
> > (/) in the first equation is at type Double -> Double -> Double.
> >
>
> Then why don't I get an error here:
>
> Prelude> 2 / 4
> 0.5
There are several things going on here. The first is that numeric
literals are overloaded; integral numeric literals (like 2) can be of
any numeric type. What actually happens is that they get wrapped in a
call to fromIntegral.
The other thing going on is ghci's type defaulting: since it doesn't
otherwise know what type this expression should be, it picks Double.
(It would also pick Integer if that worked, but Integer doesn't work
here because of the (/).)
> Prelude> 2 / fromIntegral 4
> 0.5
>From the above discussion you can see that this is exactly the same as
the first expression.
>
> And why does this happen:
>
> Prelude> let x = 2
> Prelude> :type x
> x :: Integer
This is because of the defaulting again. Since there are no
constraints on the type of x this time, it picks Integer.
> Prelude> x / fromIntegral 4
>
> <interactive>:1:0:
> No instance for (Fractional Integer)
> arising from a use of `/' at <interactive>:1:0-17
> Possible fix: add an instance declaration for (Fractional Integer)
> In the expression: x / fromIntegral 4
> In the definition of `it': it = x / fromIntegral 4
>
Of course, now that x has type Integer, this is not well-typed; you
can't divide Integers.
>
> And how do I read this type:
>
> Prelude> :type fromIntegral
> fromIntegral :: (Num b, Integral a) => a -> b
>
> What does the => mean?
The => indicates class constraints. You can read this as
"fromIntegral has type a -> b, as long as b is an instance of the Num
class, and a is an instance of the Integral class." That is,
fromIntegral can convert a value of any Integral type (Int, Integer)
to a value of any Num type.
-Brent
More information about the Beginners
mailing list