Skip to content

Instantly share code, notes, and snippets.

@paf31
Last active December 17, 2015 03:18
Show Gist options
  • Save paf31/5541732 to your computer and use it in GitHub Desktop.
Save paf31/5541732 to your computer and use it in GitHub Desktop.
A Parsec parser which only recognizes balanced binary trees.
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