Variadic functions for * and /
authorOwen Rodley <Strigoides@gmail.com>
Sat, 18 May 2013 13:59:08 +0000 (01:59 +1200)
committerOwen Rodley <Strigoides@gmail.com>
Sun, 19 May 2013 23:06:27 +0000 (11:06 +1200)
Uses a new macro DEFINE-VARIADIC-OP, which also captures a pattern used
in + and -, and is used for them as well

src/numbers.lisp

index 060e657..a3105bb 100644 (file)
 
 ;;;; Various numeric functions and constants
 
-;; Basic functions
-(defun * (x y) (* x y))
-(defun / (x y) (/ x y))
+;; TODO: Use MACROLET when it exists
+(defmacro define-variadic-op (operator initial-value)
+  (let ((init-sym   (gensym))
+        (dolist-sym (gensym)))
+    `(defun ,operator (&rest args)
+       (let ((,init-sym ,initial-value))
+         (dolist (,dolist-sym args)
+           (setq ,init-sym (,operator ,init-sym ,dolist-sym)))
+         ,init-sym))))
+
+(define-variadic-op + 0)
+(define-variadic-op - 0)
+(define-variadic-op * 1)
+(define-variadic-op / 1)
+
 (defun 1+ (x) (+ x 1))
 (defun 1- (x) (- x 1))
 
-(defun + (&rest args)
-  (let ((r 0))
-    (dolist (x args r)
-      (incf r x))))
-
-(defun - (x &rest others)
-  (if (null others)
-      (- x)
-      (let ((r x))
-        (dolist (y others r)
-          (decf r y)))))
-
 (defun truncate (x &optional (y 1))
   (floor (/ x y)))