Why can't read deduce the correct type?

后端 未结 2 1371
南方客
南方客 2021-01-15 08:43

In Haskell, I can make Haskell value from a string with read.

Prelude> read \"1\" + 3
4

I can use fst to get t

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 09:33

    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.

提交回复
热议问题