Last active
December 21, 2019 00:18
-
-
Save 3v0k4/120d00c0306ab0bf3b3f2097eb5016ef to your computer and use it in GitHub Desktop.
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
data Ast | |
= Node Op Ast Ast | |
| Value Int | |
instance showAst :: Show Ast where | |
show (Node op ast1 ast2) = "(" <> show op <> " " <> show ast1 <> " " <> show ast2 <> ")" | |
show (Value i) = show i | |
data Op | |
= Add | |
| Sub | |
instance showOp :: Show Op where | |
show Add = "Add" | |
show Sub = "Sub" | |
astParser :: Parser Ast | |
astParser = do | |
skipSpaces | |
op <- opParser | |
skipSpaces | |
ast1 <- valueParser <|> astParser | |
skipSpaces | |
ast2 <- valueParser <|> astParser | |
pure $ Node op ast1 ast2 | |
opParser :: Parser Op | |
opParser = | |
addParser <|> subParser | |
addParser :: Parser Op | |
addParser = do | |
_ <- string "add" | |
pure Add | |
subParser :: Parser Op | |
subParser = do | |
_ <- string "sub" | |
pure Sub | |
intParser :: Parser Int | |
intParser = do | |
ds <- many1 anyDigit | |
case fromString $ fromChars ds of | |
Just i -> pure i | |
Nothing -> fail "I was expecting an int!" | |
valueParser :: Parser Ast | |
valueParser = do | |
i <- intParser | |
pure $ Value i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment