Last active
October 30, 2016 13:53
-
-
Save quchen/4634782 to your computer and use it in GitHub Desktop.
Deriving a Read instance from a Parsec parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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