Macro for more than 1 line of code

I am studying the Common Lisp macro system and suddenly I discovered a problem

(defun hello () (format t "hello ~%")) (defun world () (format t "world ~%")) (defmacro call-2-func (func1 func2) `(,func1) `(,func2)) (macroexpand-1 '(call-2-func hello world)) (WORLD) T 

Well. Why can't I create 2 LoCs from just one macro? How can i work? ( progn will not work in a more difficult situation ... )

+4
source share
2 answers

A macro should return only one form that will call both functions.
Instead, you create two forms (and only the latter is used).

Try:

 (defmacro call-2-func (func1 func2) `(progn (,func1) (,func2))) 

or if you do not want to be limited to only two functions:

 (defmacro call-funcs (&rest funcs) `(progn ,@(mapcar #'list funcs))) 
+9
source

The material above was not clear, so let me add ... yes, you can return 2 lines of code from a macro, but remember that functions and macros usually return only one value. You can calculate multiple values ​​in a function, but it returns only the last value. This function below returns only value-2 (it still calculates value-1, it does nothing with value-1).

 (defun myfun () (compute-value-1) (compute-value-2)) 

If you want to return 2 values, you can either wrap them in a list (or another structure) or use the # values ​​to return more than one value.

In this case, your macro can return only one statement, unless you transfer several values ​​to the list or use the # values. What it returns must be the correct lisp code, and this is usually done using PROGN

 (defmacro call-2-func (func1 func2) `(PROGN (,func1) (,func2))) 

If you used

 (defmacro call-2-func (func1 func2) `(,func1) `(,func2)) 

Then your macro calculates 2 values, but returns only the last. (as you see in the macro exponent above)

You can easily see this with defun, which calculates 2 values, but returns only the last.

 (defun myname () 1 2) 

Using VALUES is a bit weird.

 (defmacro tttt () '(values (one) (one))) (tttt) 1 1 
0
source

All Articles