From 06bf4c656377572859846767cb9af5db8fc27893 Mon Sep 17 00:00:00 2001 From: Akshay Date: Fri, 9 Oct 2020 11:35:56 +0530 Subject: use mtl to generate errors --- src/Operators.hs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'src/Operators.hs') diff --git a/src/Operators.hs b/src/Operators.hs index e57f885..3b96281 100644 --- a/src/Operators.hs +++ b/src/Operators.hs @@ -2,9 +2,11 @@ module Operators ( primitives ) where +import Control.Monad.Except +import Error (LispError (..), LispResult (..)) import Parser -primitives :: [(String, [Expr] -> Expr)] +primitives :: [(String, [Expr] -> LispResult Expr)] primitives = [ ("+", arithmetic (+)) @@ -13,10 +15,14 @@ primitives = , ("/", arithmetic div) ] -arithmetic :: (Integer -> Integer -> Integer) -> [Expr] -> Expr -arithmetic op args = IntLiteral $ foldl1 op $ map unwrapNum args +arithmetic :: (Integer -> Integer -> Integer) -> [Expr] -> LispResult Expr +arithmetic op args + | length args < 2 = throwError $ ArgCount 2 args + | otherwise = do + as <- mapM unwrapNum args + return . IntLiteral $ foldl1 op as -unwrapNum :: Expr -> Integer -unwrapNum (IntLiteral n) = n -unwrapNum _ = undefined +unwrapNum :: Expr -> LispResult Integer +unwrapNum (IntLiteral n) = return n +unwrapNum x = throwError $ TypeMismatch "number" x -- cgit v1.2.3