Search code examples
macroscommon-lispshort-circuiting

How to implement a short-circuited "and" macro in Common Lisp?


Assume that the macro would take the boolean types a and b . If a is nil, then the macro should return nil (without ever evaluating b), otherwise it returns b. How do you do this?


Solution

  • This really depends on what you can use. E.g., is or available? if? cond?

    Here is one example:

    (defmacro and (a b)
      `(if ,a ,b nil)
    

    EDIT. In response to a comment, or is more complicated because we have to avoid double evaluation:

    (defmacro or (a b)
      (let ((v (gensym "OR")))
        `(let ((,v ,a))
           (if ,v ,v ,b))))