stack setup and integer expression parser

This commit is contained in:
vegowotenks 2024-09-15 12:39:46 +02:00
commit 165b00b54d
12 changed files with 318 additions and 0 deletions

58
src/Lib.hs Normal file
View file

@ -0,0 +1,58 @@
module Lib
(
) where
import Control.Applicative((<*))
import Data.Ratio
import Text.Parsec
import Text.Parsec.Char
import Text.Parsec.String
import Text.Parsec.Expr
import Text.Parsec.Token
import Text.Parsec.Language
data Expr = Var String | Constant Integer | Unary UnaryOperator Expr | Binary BinaryOperator Expr Expr
deriving Show
data UnaryOperator = Not
deriving Show
data BinaryOperator = Plus | Minus | Multiply | Divide
deriving Show
naturalRatio a = a % 1
def = emptyDef{ commentStart = ""
, commentEnd = ""
, identStart = letter <|> char '_'
, identLetter = alphaNum <|> char '_'
, opStart = oneOf "+-/*"
, opLetter = oneOf "+-/*"
, reservedOpNames = ["+", "-", "/", "*"]
, reservedNames = ["pi", "e"]
}
TokenParser{ parens = m_parens
, identifier = m_identifier
, reservedOp = m_reservedOp
, reserved = m_reserved
, semiSep1 = m_semiSep1
, natural = m_natural
, whiteSpace = m_whiteSpace } = makeTokenParser def
exprparser :: Parser Expr
exprparser = buildExpressionParser table term <?> "expression"
table = [
[
Infix (m_reservedOp "*" >> return (Binary Multiply)) AssocLeft,
Infix (m_reservedOp "/" >> return (Binary Divide)) AssocLeft
],
[
Infix (m_reservedOp "+" >> return (Binary Plus)) AssocLeft,
Infix (m_reservedOp "-" >> return (Binary Minus)) AssocLeft
]
]
term = m_parens exprparser
<|> fmap Var m_identifier
<|> fmap Constant m_natural