tpascale
tpascale

Reputation: 2576

Haskell read type inferences

Haskell newbie wants to know why the first 3 were ok but the 4th statement blew up:

Prelude> read "5.3" + 5.0                   -- ok
10.3

Prelude> read "5"   + 5                     -- ok
10

Prelude> read "5"   + 5.3                   -- ok
10.3

Prelude> read "5.3" + 5                     -- huh ???
*** Exception: Prelude.read: no parse

I see that :t 5.3 is Fractional whereas 5 is just Num, but both must be returnable from read because the first three commands worked, and (+) should work on any pair of Nums. What's going on here ?

Upvotes: 2

Views: 189

Answers (1)

ehird
ehird

Reputation: 40787

When the type of a numeric expression is ambiguous, Haskell tries to resolve it first to Integer, and then to Double (a floating-point number) if that doesn't work. This is because it would be pretty annoying to have to explicitly specify the types for simple arithmetic expressions.

This specific example happened because 5.3 can't be an Integer (since Integer is not Fractional), so it resolved to Double in that case. But since 5 can be an Integer, and read "5.3" can be any type that can be read, it defaulted to Integer, and blew up at runtime, since 5.3 isn't a valid Integer literal.

If you turn on -Wall, you'll be able to see this type defaulting happen; it'll show a warning when it does. (This is typically quite annoying in practice, though, since such defaulting is very common in GHCi.)

Upvotes: 9

Related Questions