From 6abe90d7cc8e0b899ea97f3b1b4fd5138ced6167 Mon Sep 17 00:00:00 2001 From: Suguivy Date: Wed, 24 Feb 2021 20:23:58 +0100 Subject: [PATCH] Added some error handling --- src/Evaluator.hs | 24 ++++++++++++------------ src/Main.hs | 7 ++++--- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/Evaluator.hs b/src/Evaluator.hs index 3efc942..3a83a07 100644 --- a/src/Evaluator.hs +++ b/src/Evaluator.hs @@ -3,17 +3,17 @@ module Evaluator where import Expression import Primitives -eval :: Expression -> Expression -eval n@(Number _) = n -eval s@(Symbol _) = s -eval (SExpr es) = apply $ SExpr (map eval es) +eval :: Expression -> Either String Expression +eval n@(Number _) = Right n +eval s@(Symbol _) = Right s +eval (SExpr es) = mapM eval es >>= apply . SExpr -apply :: Expression -> Expression +apply :: Expression -> Either String Expression apply (SExpr (f:args)) = case f of - Symbol "+" -> pAdd args - Symbol "-" -> pSub args - Symbol "*" -> pMul args - Symbol "/" -> pDiv args - Symbol _ -> error "no primitive functions not supported" - _ -> error "object not applicable" -apply _ = error "Object not applicable" + Symbol "+" -> Right $ pAdd args + Symbol "-" -> Right $ pSub args + Symbol "*" -> Right $ pMul args + Symbol "/" -> Right $ pDiv args + Symbol _ -> Left "no primitive functions not supported (only +, -, * and /)" + _ -> Left "object not applicable" +apply _ = Left "object not applicable" diff --git a/src/Main.hs b/src/Main.hs index 8c72125..43d8779 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -16,6 +16,7 @@ main = runInputT defaultSettings repl Left err -> do outputStrLn $ show err repl - Right e -> do - outputStrLn . show $ eval e - repl + Right e -> outputStrLn (case eval e of + Right out -> show out + Left err -> err) + repl