Skip to content

Instantly share code, notes, and snippets.

@Solonarv
Created January 28, 2019 03:10
Show Gist options
  • Save Solonarv/99826c2b472052c451b0f3b610bb9673 to your computer and use it in GitHub Desktop.
Save Solonarv/99826c2b472052c451b0f3b610bb9673 to your computer and use it in GitHub Desktop.
data Expr = Val Double | Op (Double -> Double -> Double) Expr Expr
binOpP :: Parser (e -> e -> e) -- ^ binary operator
-> Parser e -- ^ parser for operands
-> Parser e
binOpP opP elP = do
x <- elP
asum
[ do op <- opP; y <- binOpP opP elP; pure (op x y)
, pure x
]
exprP, addP, mulP, powP, valP :: Parser Expr
exprP = addP
addP = binOpP addOpsP mulP
where
addOpsP = asum [Op (+) <$ char '+', Op (-) <$ char '-']
mulP = binOpP mulOpsP powP
where
mulOpsP = asum [Op (*) <$ char '*', Op (/) <$ char '/']
powP = binOpP (Op (**) <$ char '^') valP
valP = (Val <$> doubleP) <|> parens exprP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment