简体   繁体   中英

Predefining functions that are automatically generated with Common Lisp macros

Macros may create functions in the global scope. For example:

(defmacro test-macro (&body functions)
 `(progn ,@(loop for function in functions
               collect `(defun ,function ()
                           *some-interesting-thing*))))

Another example (albeit with methods) would be the automatically generated accessors for a CLOS class.

The functions are not defined at macro expansion time, but rather when the generated code is compiled/interpreted. This can cause some difficulty. If these functions are being expected, a warning will be thrown. What is the idiomatic way to define these functions before they are correctly defined? One potential solution might be the following:

(defmacro test-macro (&body functions)
  (macrolet ((empty-function (name)
                `(defun ,name ())))
    (dolist (function functions)
       (empty-function function)))
  `(progn ,@(loop for function in functions
                collect `(defun ,function ()
                            *some-interesting-thing*))))

Note that the intermediate function is defined during macro expansion time.

If you need to define a function at compile time on the toplevel, then use:

(eval-when (:compile-toplevel)
  (defun foo ...))

Note that you can define a macro which generates such code. Such a form can be part of a PROGN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM