From 9e7ad28c5ccf816bbcc7bd67009955bb46edbce6 Mon Sep 17 00:00:00 2001 From: VegOwOtenks Date: Mon, 16 Sep 2024 11:38:22 +0200 Subject: [PATCH] Error out for undefined variables --- app/Main.hs | 7 ++++--- src/Lib.hs | 18 +++++++++++++----- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/app/Main.hs b/app/Main.hs index 0100982..167abc2 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -2,7 +2,7 @@ module Main (main) where import Text.Parsec -import Lib (exprparser, evaluate, replaceVars) +import Lib (exprparser, evaluate, replaceVars, Expr) import Data.Map (Map) import qualified Data.Map as Map @@ -21,8 +21,9 @@ showRatio p r = (if (r < 0) then "-" else "") ++ prepoint_digits ++ (if (length prepoint_digits = init . show . round . abs $ (r * 10) postpoint_digits = reverse .dropWhile (=='0') . reverse .(take p) . (drop (length prepoint_digits)) . show . round . abs $ (r * 10^p) -useResult (Right e) = (showRatio precision) . evaluate $ replaceVars e vars -useResult (Left e) = show e +useResult :: Either ParseError Expr -> String +useResult (Right expr) = either id ((showRatio precision) . evaluate) $ replaceVars expr vars +useResult (Left error) = show error vars :: Map String Rational vars = Map.fromList [("pi", 245850922 % 78256779), ("e", 271801 % 99990)] diff --git a/src/Lib.hs b/src/Lib.hs index 2b24d47..b9c05aa 100644 --- a/src/Lib.hs +++ b/src/Lib.hs @@ -1,5 +1,5 @@ module Lib - ( exprparser, evaluate, replaceVars + ( exprparser, evaluate, replaceVars, Expr ) where import Control.Applicative((<*)) @@ -92,10 +92,17 @@ 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 +replaceVars :: Expr -> Map.Map String Rational -> Either String Expr +replaceVars (Constant c) vs = Right $ Constant c +replaceVars (Variable name) vs = maybe (Left ("Usage of unknown variable: '" ++ name ++ "'\nSuggestion: define the variable\n++ " ++ name ++ "=42")) (Right . Constant . id) $ Map.lookup name vs +replaceVars (Binary op l r) vs = case leftBranch of + Left s -> Left s + Right a -> case rightBranch of + Left s -> Left s + Right b -> Right $ Binary op a b + where + leftBranch = replaceVars l vs + rightBranch = replaceVars r vs evaluate :: Expr -> Rational evaluate (Constant c) = c @@ -104,3 +111,4 @@ evaluate (Binary Minus a b) = evaluate a - evaluate b evaluate (Binary Divide a b) = evaluate a / evaluate b evaluate (Binary Multiply a b) = evaluate a * evaluate b evaluate (Binary Power a b) = rationalPower (evaluate a) (evaluate b) +evaluate (Variable _) = error "Unreachable Code"