Adding div and mod

This commit is contained in:
Zoe Roux
2021-11-08 18:05:35 +01:00
parent f126bea6a9
commit 5f3beea39c
2 changed files with 32 additions and 3 deletions
+2 -2
View File
@@ -62,9 +62,9 @@ evalEq [Expr exp, other] env = do
evalEq [Atom first, other] nEnv
evalEq [other, Expr exp] env = do
(first, nEnv) <- evalS exp env
evalEq [Atom first, other] nEnv
evalEq [other, Atom first] nEnv
evalEq [Atom (AQuote quoted), other] env = evalEq [Atom quoted, other] env
evalEq [other, Atom (AQuote quoted)] env = evalEq [Atom quoted, other] env
evalEq [other, Atom (AQuote quoted)] env = evalEq [other, Atom quoted] env
evalEq _ _ = Left "**Error: Invalid arguments in eq?**"
evalAtom :: [Statement] -> LispEnv -> Either String (Atom, LispEnv)
+30 -1
View File
@@ -6,7 +6,9 @@ mathEnv :: LispEnv
mathEnv = [
("+", ABuiltin "+" evalPlus),
("-", ABuiltin "-" evalMinus),
("*", ABuiltin "*" evalMult)
("*", ABuiltin "*" evalMult),
("div", ABuiltin "div" evalDiv),
("mod", ABuiltin "mod" evalMod)
]
evalPlus :: [Statement] -> LispEnv -> Either String (Atom, LispEnv)
@@ -44,3 +46,30 @@ evalMult (x:xs) env = do
(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)
evalDiv :: [Statement] -> LispEnv -> Either String (Atom, LispEnv)
evalDiv [_, Atom (AInt 0)] env = Left "**Error: Division by 0 is undefined.**"
evalDiv [_, Atom (AFloat 0)] env = Left "**Error: Division by 0 is undefined.**"
evalDiv [Atom (AInt f), Atom (AInt s)] env = Right (AInt (f `div` s), env)
evalDiv [Atom (AFloat f), Atom (AFloat s)] env = Right (AFloat (f / s), env)
evalDiv [Atom (AFloat f), Atom (AInt s)] env = Right (AFloat (f / fromIntegral s), env)
evalDiv [Atom (AInt f), Atom (AFloat s)] env = Right (AFloat (fromIntegral f / s), env)
evalDiv [Expr expr, other] env = do
(res, nEnv) <- evalS expr env
evalDiv [Atom res, other] nEnv
evalDiv [other, Expr expr] env = do
(res, nEnv) <- evalS expr env
evalDiv [other, Atom res] nEnv
evalDiv _ _ = Left "**Error: Invalid arguments in div.**"
evalMod :: [Statement] -> LispEnv -> Either String (Atom, LispEnv)
evalMod [_, Atom (AInt 0)] env = Left "**Error: mod by 0 is undefined.**"
evalMod [_, Atom (AFloat 0)] env = Left "**Error: mod by 0 is undefined.**"
evalMod [Atom (AInt f), Atom (AInt s)] env = Right (AInt (f `mod` s), env)
evalMod [Expr expr, other] env = do
(res, nEnv) <- evalS expr env
evalMod [Atom res, other] nEnv
evalMod [other, Expr expr] env = do
(res, nEnv) <- evalS expr env
evalMod [other, Atom res] nEnv
evalMod _ _ = Left "**Error: Invalid arguments in mod.**"