From f126bea6a9181278fe5a01604e15fd17f3ae847b Mon Sep 17 00:00:00 2001 From: Zoe Roux Date: Mon, 8 Nov 2021 16:36:04 +0100 Subject: [PATCH] Adding - and * --- src/Maths.hs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/Maths.hs b/src/Maths.hs index 169d686..b7d3556 100644 --- a/src/Maths.hs +++ b/src/Maths.hs @@ -4,7 +4,9 @@ import Evaluator mathEnv :: LispEnv mathEnv = [ - ("+", ABuiltin "+" evalPlus) + ("+", ABuiltin "+" evalPlus), + ("-", ABuiltin "-" evalMinus), + ("*", ABuiltin "*" evalMult) ] evalPlus :: [Statement] -> LispEnv -> Either String (Atom, LispEnv) @@ -16,5 +18,29 @@ evalPlus (x:xs) env = do (AFloat f, AFloat s) -> Right (AFloat $ f + s, nnEnv) (AFloat f, AInt s) -> Right (AFloat $ f + fromIntegral s, nnEnv) (AInt f, AFloat s) -> Right (AFloat $ fromIntegral f + s, nnEnv) - (value, _) -> Left $ "**Error: \"" ++ show value ++"\" is not a number **" + (value, _) -> Left $ "**Error: \"" ++ show value ++ "\" is not a number **" evalPlus [] env = Right (AInt 0, env) + +evalMinus :: [Statement] -> LispEnv -> Either String (Atom, LispEnv) +evalMinus (x:xs) env = do + (value, nEnv) <- eval x env + (rest, nnEnv) <- evalPlus xs nEnv + case (value, rest) of + (AInt f, AInt s) -> Right (AInt $ f - s, nnEnv) + (AFloat f, AFloat s) -> Right (AFloat $ f - s, nnEnv) + (AFloat f, AInt s) -> Right (AFloat $ f - fromIntegral s, nnEnv) + (AInt f, AFloat s) -> Right (AFloat $ fromIntegral f - s, nnEnv) + (value, _) -> Left $ "**Error: \"" ++ show value ++ "\" is not a number **" +evalMinus [] env = Right (AInt 0, env) + +evalMult :: [Statement] -> LispEnv -> Either String (Atom, LispEnv) +evalMult (x:xs) env = do + (value, nEnv) <- eval x env + (rest, nnEnv) <- evalPlus xs nEnv + case (value, rest) of + (AInt f, AInt s) -> Right (AInt $ f * s, nnEnv) + (AFloat f, AFloat s) -> Right (AFloat $ f * s, nnEnv) + (AFloat f, AInt s) -> Right (AFloat $ f * fromIntegral s, nnEnv) + (AInt f, AFloat s) -> Right (AFloat $ fromIntegral f * s, nnEnv) + (value, _) -> Left $ "**Error: \"" ++ show value ++ "\" is not a number **" +evalMult [] env = Right (AInt 1, env)