10

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?

cafce25
  • 15,907
  • 4
  • 25
  • 31
sergeantSalty
  • 179
  • 1
  • 1
  • 10
  • I do not quite understand how I can use the function. for example: If I have the String "123", how can I cast it into an Integer ? And more general, can 'a' be any type (list, integer, pair...), or are their limited possibilities to typecast the String? – sergeantSalty Mar 04 '18 at 19:52
  • Well the type signature already explains it: it can convert a `String` in any type `a` where `Read a` holds. You can explicitly specify the type, for example `read "123" :: Int`. – Willem Van Onsem Mar 04 '18 at 19:54
  • short and clear, thank you @WillemVanOnsem ! – sergeantSalty Mar 04 '18 at 20:01

1 Answers1

11

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.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117