From 7f28dc939fca2e1ea4357d4b1a183d9d9625aa51 Mon Sep 17 00:00:00 2001 From: sudoer777 Date: Thu, 7 Sep 2023 23:13:47 -0500 Subject: [PATCH] Move parser to separate file --- app/Main.hs | 47 ++-------------------------------------- app/Parser/Equation.hs | 49 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 45 deletions(-) create mode 100644 app/Parser/Equation.hs diff --git a/app/Main.hs b/app/Main.hs index b54a46c..7ae4b5f 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -1,53 +1,10 @@ module Main (main) where -import Control.Monad.Combinators.Expr -import Data.Void (Void) +import Parser.Equation import System.Environment import Text.Megaparsec -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 - -symbolParser :: String -> Parser String -symbolParser = L.symbol C.space - -intParser :: Parser Int -intParser = lexemeParser L.decimal - -term :: Parser Expr -term = Int <$> intParser - -table :: [[Operator Parser Expr]] -table = - [ [ binaryOp "*" Mul, - binaryOp "/" Div - ], - [ binaryOp "+" Add, - binaryOp "-" Sub - ] - ] - -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) "" -- main :: IO () main = do input <- fmap head getArgs - parseTest expr input \ No newline at end of file + parseTest equationParser input \ No newline at end of file diff --git a/app/Parser/Equation.hs b/app/Parser/Equation.hs new file mode 100644 index 0000000..4f39b1c --- /dev/null +++ b/app/Parser/Equation.hs @@ -0,0 +1,49 @@ +module Parser.Equation (equationParser) where + +import Control.Monad.Combinators.Expr +import Data.Void (Void) +import Text.Megaparsec +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 + +symbolParser :: String -> Parser String +symbolParser = L.symbol C.space + +intParser :: Parser Int +intParser = lexemeParser L.decimal + +term :: Parser Expr +term = Int <$> intParser + +table :: [[Operator Parser Expr]] +table = + [ [ binaryOp "*" Mul, + binaryOp "/" Div + ], + [ binaryOp "+" Add, + binaryOp "-" Sub + ] + ] + +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) "" + +equationParser = expr \ No newline at end of file