Skip to content

Instantly share code, notes, and snippets.

@quchen
Last active October 30, 2016 13:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quchen/4634782 to your computer and use it in GitHub Desktop.
Save quchen/4634782 to your computer and use it in GitHub Desktop.
Deriving a Read instance from a Parsec parser
import Text.Parsec hiding ((<|>), many)
import Text.Parsec.String
import Text.Printf
import Control.Applicative
data MyType = Single Int
| Tuple MyType MyType
instance Show MyType where
show (Single x) = show x
show (Tuple x y) = printf "(%s %s)" (show x) (show y)
-- > print $ Tuple (Tuple (Single 1) (Single 2)) (Single 3)
-- >>> ((1 2) 3)
tupleP :: Parser MyType
tupleP = between (char '(') (char ')') $
Tuple <$> myTypeP <* space <*> myTypeP
-- Don't worry about read failing, in production code there's
-- better ways of doing this of course. Here it's just a hack
-- to make this code shorter.
singleP :: Parser MyType
singleP = Single . read <$> many1 digit
myTypeP :: Parser MyType
myTypeP = tupleP <|> singleP
-- > parse tupleP "" "((1 2) 3)"
-- >>> Right ((1 2) 3)
instance Read MyType where
readsPrec = undefined -- ?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment