And / Or Macros for LISP

In case LISP programmers would like to implement && and || operators, the way they exist in C, the way to do that is as follows:


(defmacro && (head &rest tail)
    (if (eval head)
        (if (null tail)
            T
            `(&& ,@tail) ) ) )

(defmacro || (head &rest tail)
    (if (eval head)
        T
        (if (null tail)
            NIL
            `(|| ,@tail) ) ) )


Bear In Mind, within LISP, Not every successful function-call returns non-NIL. Therefore, I would use a slightly fancier approach, if any…

(Edit 10/02/2016 : )

 



(intern "IGN" :KEYWORD)
(intern "ign" :keyword)

(defun eval-list (input)
    (cond
        ((null input) NIL)
        ((null (listp input))
            (list (eval input)) )
        ((null (listp (car input)))
            (list (eval input)) )
        (T (cons (eval (car input))
            (eval-list (cdr input)) ) ) ) )

(defmacro && ((head T) &rest tail)
    (if (eq head :IGN)
        (progn (eval-list (car tail))
            `(&& ,@(cdr tail)) )
        (if (eval head)
            (if (null tail)
                T
                `(&& ,@tail) ) ) ) )

(defmacro || ((head NIL) &rest tail)
    (if (eq head :IGN)
        (progn (eval-list (car tail))
            `(|| ,@(cdr tail)) )
        (if (eval head)
            T
            (if (null tail)
                NIL
                `(|| ,@tail) ) ) ) )

 

Dirk

 

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *

Please Prove You Are Not A Robot *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>