Haskell's read function explanation
Asked Answered
B

1

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?

Bushweller answered 4/3, 2018 at 19:45 Comment(3)
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?Bushweller
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.Gyron
short and clear, thank you @WillemVanOnsem !Bushweller
C
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.

Creativity answered 4/3, 2018 at 20:2 Comment(1)
Thank you, that was a good explanation. I´ve played around with read now and it become clear to me.Bushweller

© 2022 - 2024 — McMap. All rights reserved.