Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-safe `read` in Haskell

Tags:

haskell

Learn You a Haskell discusses the following data type:

data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday   
           deriving (Eq, Ord, Show, Read, Bounded, Enum)  

The book demonstrates how to use read to parse a String into a Day type.

$ read "Saturday" :: Day
Saturday

However, I can pass in a non-Day value, resulting in an exception.

$ read "foo" :: Day
*** Exception: Prelude.read: no parse

What's a type-safe way to use read in the above example?

like image 445
Kevin Meredith Avatar asked May 26 '14 02:05

Kevin Meredith


People also ask

What is nil Haskell?

The Nil constructor is an empty list. It contains no objects. So any time you're using the [] expression, you're actually using Nil . Then the second constructor concatenates a single element with another list.

What is show in Haskell?

The shows functions return a function that prepends the output String to an existing String . This allows constant-time concatenation of results using function composition.


1 Answers

In addition to the old standard function reads mentioned by @JonPurdy, there's also the more recently added

Text.Read.readMaybe :: Read a => String -> Maybe a

which is simpler to use when the string contains just one value to parse.

like image 125
Ørjan Johansen Avatar answered Sep 30 '22 12:09

Ørjan Johansen