Last active
December 17, 2015 03:18
-
-
Save paf31/5541732 to your computer and use it in GitHub Desktop.
A Parsec parser which only recognizes balanced binary trees.
This file contains hidden or 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 | |
| data Tree a = Tip a | Branch (Tree (a, a)) deriving (Show) | |
| tree :: Parsec String u (Tree Int) | |
| tree = tree' $ do | |
| ds <- many digit | |
| return $ read ds | |
| where | |
| tree' :: Parsec String u a -> Parsec String u (Tree a) | |
| tree' next = (between (char '(') (char ')') | |
| $ fmap Branch | |
| $ tree' | |
| $ do | |
| x <- next | |
| char ',' | |
| y <- next | |
| return $ (x, y)) <|> fmap Tip next | |
| -- ghci> parse tree "(1,2)" | |
| -- Right (Branch (Tip (1,2))) | |
| -- ghci> parseTest tree "((1,2,3,4))" | |
| -- Right (Branch (Branch (Tip ((1,2),(3,4))))) | |
| -- ghci> parseTest tree "((1,2,3))" | |
| -- parse error at (line 1, column 8): | |
| -- unexpected ")" | |
| -- expecting digit or "," |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment