replacing Variables with constant values

This commit is contained in:
vegowotenks 2024-09-15 17:58:43 +02:00
parent ff5197de5c
commit b4bbd298a0
3 changed files with 13 additions and 2 deletions

View file

@ -1,9 +1,11 @@
module Lib
( exprparser, evaluate
( exprparser, evaluate, replaceVars
) where
import Control.Applicative((<*))
import Data.Ratio
import Data.Map (Map)
import qualified Data.Map as Map
import Text.Parsec
import Text.Parsec.Char
@ -26,7 +28,7 @@ def = emptyDef{ commentStart = ""
, opStart = oneOf "+-/*^"
, opLetter = oneOf "+-/*^"
, reservedOpNames = ["+", "-", "/", "*", "^"]
, reservedNames = ["pi", "e"]
, reservedNames = []
}
TokenParser{ parens = m_parens
@ -89,6 +91,11 @@ term = m_parens exprparser
<|> fmap Constant constantInteger
<|> fmap Constant constantRational
replaceVars :: Expr -> Map.Map String Rational -> Expr
replaceVars (Variable name) vs = Constant . maybe (0 % 1) id $ Map.lookup name vs
replaceVars (Binary op a b) vs = Binary op (replaceVars a vs) (replaceVars b vs)
replaceVars (Constant c) vs = Constant c
evaluate :: Expr -> Rational
evaluate (Constant c) = c
evaluate (Binary Plus a b) = evaluate a + evaluate b