Haskell: read does not parse floating point numbers without explicit type

Consider the following function

add1 :: Num a => a -> a
add1 x = x + 1

and the following applications

*Main> add1 2
3
*Main> add1 2.2
3.2
*Main> add1 (read "1")
2
add1 (read "1.5"::Float)
2.5
*Main> add1 (read "1.5")
*** Exception: Prelude.read: no parse

Why add1doesn't the last value work for floating point numbers, but work for integers? Why should I specify the type in this case?

+4
source share
1 answer

GHCi gives type

> :t add1 (read "1.5")
add1 (read "1.5") :: (Read a, Num a) => a

, . GHCi print ed, GHCi a. GHCi a = Integer. , ( , ) (, String), (, "1.5"). Integer Read, Num, .

GHCi (), Integer, Double - , default.

> add1 (read "1.5") :: Integer
*** Exception: Prelude.read: no parse

. :

> add1 (read "1.5") :: Float
2.5
+8

Source: https://habr.com/ru/post/1599829/


All Articles