Page 2 of 2

Re: macro for looping over functions in a list

Posted: Thu Dec 23, 2010 1:27 pm
by imba
So what's wrong with the following code?

Code: Select all

(defconstant +Functions+ '(1+ 1-))

(defun compile-Function (Function)
  `((let ((val (funcall ,Function 4)))
          (if (>= val 0)
              val
            (return-From evaluate -100)))))

(defun compile-Functions (Functions)
  `(defun evaluate ()
     (+ ,@(loop for Function from Functions
               append (compile-Function Function)))))

Re: macro for looping over functions in a list

Posted: Thu Dec 23, 2010 2:39 pm
by ramarren
Looping in a list is achieved with IN keyword, not FROM, which is numeric. And if you want to funcall by name then you need to quote your symbols, although I thought the point of this was to call the function directly? Also, indirect dependency on block name like this is bad style. And there are problems with variable capture. Something like this will work when used as a macroexpander function:

Code: Select all

(eval-when (:execute :compile-toplevel :load-toplevel)
  (defconstant +functions+ '(1+ 1-)))

(defun compile-function (function block-name)
  (let ((val (gensym)))
   `((let ((,val (,function 4)))
       (if (>= ,val 0)
           ,val
           (return-from ,block-name -100))))))

(defun compile-functions (functions)
  `(defun evaluate ()
     (+ ,@(loop for function in functions
                append (compile-function function 'evaluate)))))
On Lisp by Paul Graham explains a lot about macro programming, and it is available for free.

Re: macro for looping over functions in a list

Posted: Fri Dec 24, 2010 2:38 am
by imba
Thank you very much for your patience!