functionhaskellhaskell-prelude

Haskell's read function explanation


I wonder if someone is familiar with the Prelude´s read function in Haskell.

The type of this function is following.

Read a => String -> a

Can someone explain me with a few examples how this function can be used and into what types the String can be cast?


Solution

  • Read a => String -> a means that a can be any type that is an instance of the Read class. For a type to satisfy that requirement, it has to at the very least have an implementation of either of Read's readPrec or readsPrec functions. Many built in types aready supply an implementation, and you can use deriving to generate an implementation for your own custom data types.

    To specify what you want to read the string as, you can type annotate the call directly:

    read "1" :: Int
    

    Or give the function enclosing the call to read a signature so the compiler can figure out what you want:

    myFunc :: String -> Int
    myFunc s = read s
    

    The signature says that the function returns an Int, so the compiler can infer what type to read s as since myFunc returns whatever the call to read evaluated to.