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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With