aboutsummaryrefslogtreecommitdiff
path: root/src/parser/Expr.hs
diff options
context:
space:
mode:
Diffstat (limited to 'src/parser/Expr.hs')
-rw-r--r--src/parser/Expr.hs50
1 files changed, 32 insertions, 18 deletions
diff --git a/src/parser/Expr.hs b/src/parser/Expr.hs
index 2d6937a..6a721f8 100644
--- a/src/parser/Expr.hs
+++ b/src/parser/Expr.hs
@@ -12,28 +12,42 @@ imaginaryP = Imaginary <$> (floatP <* char 'i')
rationalP :: Parser Expr
rationalP = Rational <$> floatP
+-- Parse a matrix in the following format:
+-- [ [a, b]; [c, d] ]
matrixP :: Parser Expr
-matrixP = Matrix <$> (char '[' *> sepBy (char ';') matrixRowP <* char ']')
- where matrixRowP = char '[' *> sepBy (char ',') exprP <* char ']'
+matrixP = Matrix <$> brackets (matrixRowP `sepBy` (char ';'))
+ where matrixRowP = brackets (exprP `sepBy` (char ','))
+ brackets = between "[" "]"
+
+-- Parse expression separated by one infix operator of the operator list
+operatorChoiceChain :: Parser a -> [Parser (a -> a -> a)] -> Parser a
+operatorChoiceChain x operators = x `chainl1` choice operators
+
+-- Parse an expression (lowest operator priority)
exprP :: Parser Expr
-exprP = termP `chainl1` termOpP
- where termOpP = infixOp "+" Add <|> infixOp "-" Sub
+exprP = operatorChoiceChain termP
+ [ infixOp "+" Add
+ , infixOp "-" Sub
+ ]
termP :: Parser Expr
-termP = factorP `chainl1` factorOpP
- where factorOpP = infixOp "**" Dot <|> infixOp "*" Mul <|> infixOp "/" Div <|> infixOp "%" Mod
+termP = operatorChoiceChain factorP
+ [ infixOp "**" Dot
+ , infixOp "*" Mul
+ , infixOp "/" Div
+ , infixOp "%" Mod
+ ]
factorP :: Parser Expr
-factorP = endpointP `chainl1` expOpP
- where expOpP = infixOp "^" Exp
-
- endpointP = parensExprP
- <|> imaginaryP
- <|> rationalP
- <|> matrixP
- <|> functionP
- <|> variableP
- where variableP = Variable <$> alphaStringP
- functionP = Function <$> alphaStringP <*> parensExprP
- parensExprP = parenthesize exprP
+factorP = choice [ parenthesizedExprP
+ , imaginaryP
+ , rationalP
+ , matrixP
+ , functionP
+ , variableP
+ ] `chainl1` (infixOp "^" Exp)
+
+ where variableP = Variable <$> alphaStringP
+ functionP = Function <$> alphaStringP <*> parenthesizedExprP
+ parenthesizedExprP = parenthesis exprP