Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell read type inferences

Tags:

haskell

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 ?

like image 621
tpascale Avatar asked Jul 02 '26 17:07

tpascale


1 Answers

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.)

like image 156
ehird Avatar answered Jul 05 '26 16:07

ehird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!