In Haskell, I can make Haskell value from a string with read
.
Prelude> read \"1\" + 3
4
I can use fst
to get t
First, let's see the type signature of read
:
Prelude> :t read
read :: Read a => String -> a
As you can see, its return value must have a type of the Read
typeclass. However, if we don't use the value the complier won't know what type it is.
In such cases, we can add ::
to specify its type.
Prelude> read "5"
*** Exception: Prelude.read: no parse
Prelude> read "5" :: Int
5
Similarly,
Prelude> read "(1, 2)"
*** Exception: Prelude.read: no parse
Prelude> read "(1, 2)" :: (Int, Int)
(1,2)
Prelude> fst (read "(1,2)" :: (Int, Int))
1
The compiler can deduce the types most of the time, but when it meets read "5"
, it may get confused about whether the type should be Int
or Float
or anything else. Only after computing, Haskell can know its type. On the other hand, Haskell has static types, so it has to know all type before compiling.