blueMountain
blueMountain

Reputation: 23

Haskell read function with no annotation

Does haskell read function implicitly converts a data type into another?

import IO

main = do
    putStrLn "Enter an interger: "
    num <- getLine
    putStr "Value + 3 is "
    putStrLn (show((read num) + 3))

So, haskell interpreter automatically changes num's data type from string to int to handle '+ 3'?

Upvotes: 0

Views: 96

Answers (2)

chi
chi

Reputation: 116174

Here you are using

show :: Show a => a -> String
read :: Read a => String -> a
(+) :: Num a => a -> a -> a
3 :: Num a => a

on the same type a. So, Haskell searches for a type a satisfying Show a, Read a, Num a.

In principle, this would be rejected since the type is ambiguous, but Haskell mandates a special rules for Num, causing a to be defaulted, usually to Integer. Since that satisfies also Show and Read, the program type-checks.

Upvotes: 1

Noughtmare
Noughtmare

Reputation: 10685

read has type Read a => String -> a, which means that it can convert a String into any type that is an instance of the Read type class. Which type it will use depends on the surrounding code. In this case you write read num + 3. The + operator is also overloaded to work for any type that is an instance of Num, so the type of read num + 3 is (Read a, Num a) => a. Haskell has a mechanism that chooses a default type whenever the Num type class remains in the final type of an expression. In this case it defaults to Integer, so the final type is Integer.

You can see this in action by enabling the -Wtype-defaults warning which is also included in -Wall:

Test.hs:5:15: warning: [-Wtype-defaults]
    • Defaulting the following constraints to type ‘Integer’
        (Show a0) arising from a use of ‘show’ at Test.hs:5:15-34
        (Num a0) arising from a use of ‘+’ at Test.hs:5:20-33
        (Read a0) arising from a use of ‘read’ at Test.hs:5:21-28
    • In the first argument of ‘putStrLn’, namely
        ‘(show ((read num) + 3))’
      In a stmt of a 'do' block: putStrLn (show ((read num) + 3))
      In the expression:
        do putStrLn "Enter an interger: "
           num <- getLine
           putStr "Value + 3 is "
           putStrLn (show ((read num) + 3))
  |
5 |     putStrLn (show((read num) + 3))
  |      

Upvotes: 1

Related Questions