Why is it that I can do:
1 + 2.0
but when I try:
let a = 1
let b = 2.0
a + b
<interactive>:1:5:
Couldn't match expected type `Integer' with actual type `Double'
In the second argument of `(+)', namely `b'
In the expression: a + b
In an equation for `it': it = a + b
This seems just plain weird! Does it ever trip you up?
P.S.: I know that “1” and “2.0” are polymorphic constants. That is not what worries me. What worries me is why haskell does one thing in the first case, but another in the second!
You can use GHCI to learn a little more about this. Use the command
:tto get the type of an expression.So
1is a constant which can be any numeric type (Double,Integer, etc.)So in this case, Haskell inferred the concrete type for
aisInteger. Similarly, if you writelet b = 2.0then Haskell infers the typeDouble. Usingletmade Haskell infer a more specific type than (perhaps) was necessary, and that leads to your problem. (Someone with more experience than me can perhaps comment as to why this is the case.) Since(+)has typeNum a => a -> a -> a, the two arguments need to have the same type.You can fix this with the
fromIntegralfunction:This function converts integer types to other numeric types. For example: