[Haskell-beginners] The type class Read
Francesco Ariis
fa-ml at ariis.it
Thu Jul 12 11:14:32 UTC 2018
Hello Patrik,
On Thu, Jul 12, 2018 at 12:05:52PM +0200, mrx wrote:
> Why is the type class called `Read`?
> What am I missing above?
we can say any instance of `Read` has to implement
read :: Read a => String -> a
-- the actual instance implements a different function,
-- but that's not relevant for our example
So, a typeclass (Read, capital `r`) gives us a function (`read`,
lower-case `r`). The function goes from `String` (and no other
things) to our implemented type.
As you discovered, the conversion happens at runtime, the compiler
has no way to check it beforehand, and things might explode during
execution
λ> read "18" :: Char
*** Exception: Prelude.read: no parse
λ> read "diciotto" :: Int
*** Exception: Prelude.read: no parse
It is often a good idea to use `readMay` (from Safe) to handle
failures locally without throwing an exception
readMay :: Read a => String -> Maybe a
Does this answers your question? If you have any further doubts,
shoot again
-F
More information about the Beginners
mailing list