aboutsummaryrefslogtreecommitdiff
path: root/src/Operators.hs
diff options
context:
space:
mode:
Diffstat (limited to 'src/Operators.hs')
-rw-r--r--src/Operators.hs18
1 files changed, 12 insertions, 6 deletions
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 (
2 primitives 2 primitives
3 ) where 3 ) where
4 4
5import Control.Monad.Except
6import Error (LispError (..), LispResult (..))
5import Parser 7import Parser
6 8
7primitives :: [(String, [Expr] -> Expr)] 9primitives :: [(String, [Expr] -> LispResult Expr)]
8primitives = 10primitives =
9 [ 11 [
10 ("+", arithmetic (+)) 12 ("+", arithmetic (+))
@@ -13,10 +15,14 @@ primitives =
13 , ("/", arithmetic div) 15 , ("/", arithmetic div)
14 ] 16 ]
15 17
16arithmetic :: (Integer -> Integer -> Integer) -> [Expr] -> Expr 18arithmetic :: (Integer -> Integer -> Integer) -> [Expr] -> LispResult Expr
17arithmetic op args = IntLiteral $ foldl1 op $ map unwrapNum args 19arithmetic op args
20 | length args < 2 = throwError $ ArgCount 2 args
21 | otherwise = do
22 as <- mapM unwrapNum args
23 return . IntLiteral $ foldl1 op as
18 24
19unwrapNum :: Expr -> Integer 25unwrapNum :: Expr -> LispResult Integer
20unwrapNum (IntLiteral n) = n 26unwrapNum (IntLiteral n) = return n
21unwrapNum _ = undefined 27unwrapNum x = throwError $ TypeMismatch "number" x
22 28