macro for looping over functions in a list

Discussion of Common Lisp
imba
Posts: 35
Joined: Sun Nov 21, 2010 2:13 pm

Re: macro for looping over functions in a list

Post by imba » Thu Dec 23, 2010 1:27 pm

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)))))

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: macro for looping over functions in a list

Post by ramarren » Thu Dec 23, 2010 2:39 pm

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.

imba
Posts: 35
Joined: Sun Nov 21, 2010 2:13 pm

Re: macro for looping over functions in a list

Post by imba » Fri Dec 24, 2010 2:38 am

Thank you very much for your patience!

Post Reply