Skip to content

Instantly share code, notes, and snippets.

@bavardage
Created September 1, 2010 15:53
Show Gist options
  • Save bavardage/560900 to your computer and use it in GitHub Desktop.
Save bavardage/560900 to your computer and use it in GitHub Desktop.
import Control.Monad.State
data Tree = Tree [Tree] | Node String deriving Show
type Parse a = (a, String)
(<~>) :: Parse a -> (a -> b) -> Parse b
(x,y) <~> f = (f x, y)
(<:>) :: Parse a -> (String -> Parse [a]) -> Parse [a]
(a,b) <:> f = (f b) <~> (a:)
parseTree :: String -> Parse Tree
parseTree xs = parseNodes xs <~> Tree
parseNodes :: String -> Parse [Tree]
parseNodes [] = ([], "")
parseNodes ('(':xs) = parseTree xs <:> parseNodes
parseNodes (')':xs) = ([], xs)
parseNodes xs = parseString xs <~> Node <:> parseNodes
parseString :: String -> Parse String
parseString "" = ("", "")
parseString xxs@(x:xs) | x `elem` "()" = ("", xxs)
| otherwise = parseString xs <~> (x:)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment