Type-safe `read` in Haskell

Teach you Haskell discusses the following data type:

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

The book shows how to use readto parse strings into types Day.

$ read "Saturday" :: Day
Saturday

However, I can pass a value other than the day, resulting in an exception.

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

What is the safe type of use readin the example above?

+4
source share
2 answers

In addition to the old standard feature readsmentioned by @JonPurdy, there is more recently added

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

which is easier to use when a string contains only one value for parsing.

+12
source

reads, :

reads :: Read a => ReadS a
type ReadS a = String -> [(a, String)]

, :

case reads x of

  -- foo
  [] -> Left "no parse"

  -- Saturday
  [(day, "")] -> Right (day :: Day)

  -- Fridayum
  [(_, junk)] -> Left $ "day followed by extra junk: " ++ junk

  _ -> Left "ambiguous parse"

, , GHC...

, () Parsec:

day :: Parser Day
day = choice
  [ Monday <$ string "Monday"
  , ...
  ] <* eof

, , , Parsecs parse, .

+10

Source: https://habr.com/ru/post/1541983/


All Articles