how do I define this conditional inside a defmacro?

Discussion of Common Lisp

how do I define this conditional inside a defmacro?

Postby joeish80829 » Mon May 05, 2014 2:14 am

When I run this macro as `(bool :true)` I get:

The function COMMON-LISP:T is undefined.

How do I change this macro so I can run `(bool :true)` and get `1` without really changing anything else about that's not necessary. As a defun, the below works btw. Thanks in advance for any help on this:)

Code: Select all
      (defmacro bool (&rest args)
         ` (cond ((eq (first ,args) nil) (princ nil))

           ((eq :true (first ,args)) (princ 1))

           (t nil)))
joeish80829
 
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

Re: how do I define this conditional inside a defmacro?

Postby porky11 » Mon May 05, 2014 6:07 am

Try to macroexpand your macro:
Code: Select all
(macroexpand '(bool :true))

You'll get this:
Code: Select all
(IF (EQ (FIRST (:TRUE)) NIL) (PRINC NIL)
  (IF (EQ :TRUE (FIRST (:TRUE))) (PRINC 1) NIL))


:true will be evaluated as a function

you have to write instead of ,args:
',args if you don't want the args to be evaluated, or
(list ,@args) if you want the args to be evaluated.

(and you should define it at the beginning of the macrodefinition, so it has not to be evaluated twice)

For example you could write this:
Code: Select all
(defmacro bool (&rest args)
  (let ((x (gensym)))
   `(let ((,x (first ',args)))
      (cond ((eq ,x nil)
             (princ nil))
            ((eq :true ,x)
             (princ 1))
            (t nil)))))
porky11
 
Posts: 9
Joined: Fri May 02, 2014 6:46 am

Re: how do I define this conditional inside a defmacro?

Postby joeish80829 » Tue May 06, 2014 3:18 am

Thanks alot ...that's exactly what I was looking for,

Take care
joeish80829
 
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

Re: how do I define this conditional inside a defmacro?

Postby joeish80829 » Sun May 11, 2014 4:03 am

Thanks again...just realized what (list ,@args) was for...now thanks to you I finally "get" defmacro
joeish80829
 
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am


Return to Common Lisp

Who is online

Users browsing this forum: logxor and 2 guests