Add solving expressions

main
Ethan Reece 2023-09-08 00:53:11 -05:00
parent 7f28dc939f
commit af50529dc1
Signed by: me
GPG Key ID: D3993665FF92E1C3
5 changed files with 57 additions and 18 deletions

View File

@ -27,3 +27,4 @@ Main repo: https://git.sudoer.ch/me/really-bad-compiler-in-haskell
- IDE: VSCodium
- Git platform: Forgejo
- AI: Phind
- Search: Kagi, Stack Overflow

View File

@ -0,0 +1,13 @@
module Eval.Expression (evalExpr) where
import Objects.Expression
eval :: Expr -> Int
eval (Lit x) = x
eval (Add x y) = eval x + eval y
eval (Sub x y) = eval x - eval y
eval (Mul x y) = eval x * eval y
eval (Div x y) = eval x `div` eval y
evalExpr :: Expr -> Int
evalExpr = eval

View File

@ -1,10 +1,21 @@
module Main (main) where
import Parser.Equation
import Data.Either
import Eval.Expression
import Objects.Expression
import Parser.Expression
import System.Environment
import Text.Megaparsec
-- main :: IO ()
parseResult :: ParseResult
parseResult = parseExpr "2+3*4"
getRight :: ParseResult -> Expr
getRight (Right r) = r
expr = getRight parseResult
result = evalExpr expr
main = do
input <- fmap head getArgs
parseTest equationParser input
print result

View File

@ -0,0 +1,19 @@
module Objects.Expression
( Expr
( Lit,
Add,
Sub,
Mul,
Div
),
-- solve,
)
where
data Expr
= Lit Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
deriving (Show)

View File

@ -1,21 +1,14 @@
module Parser.Equation (equationParser) where
module Parser.Expression (parseExpr, ParseResult) where
import Control.Monad.Combinators.Expr
import Data.Void (Void)
import Text.Megaparsec
import Objects.Expression
import Text.Megaparsec as MP
import Text.Megaparsec.Char as C
import Text.Megaparsec.Char.Lexer as L
type Parser = Parsec Void String
data Expr
= Int Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
deriving (Show)
lexemeParser :: Parser a -> Parser a
lexemeParser = L.lexeme C.space
@ -26,7 +19,7 @@ intParser :: Parser Int
intParser = lexemeParser L.decimal
term :: Parser Expr
term = Int <$> intParser
term = Lit <$> intParser
table :: [[Operator Parser Expr]]
table =
@ -43,7 +36,9 @@ binaryOp name f = InfixL (f <$ symbolParser name)
expr :: Parser Expr
expr = makeExprParser term table
parseExpr :: String -> Either (ParseErrorBundle String Void) Expr
parseExpr = parse (C.space *> expr <* eof) ""
type ParseResult = Either (ParseErrorBundle String Void) Expr
equationParser = expr
parseExpr :: String -> ParseResult
parseExpr = MP.parse (C.space *> expr <* eof) ""
-- parseE = parseExpr