Applying and And or In Emacs

Zach Beane has a nice Common Lisp tip about applying and. The problem that the tip addresses is how to apply and to a list of values to test that they are all true. One might think that you could simply use apply in the normal way

(apply #'and list)

but and is a macro so this doesn’t work. The solution is to use the every function like this

(every #'identity list)

This will return t if every element of list is t. All this is also true of Emacs Lisp so it’s worth mentioning in an Elisp context too.

Although Beane doesn’t mention it, the same problem exists for or. The way to handle or is with the some function

(some #'identity list)

The some function will return the first true element in the list or nil if there is none.

Longtime readers will remember that we’ve talked about some before. Both some and every are a bit more general than I’ve indicated here. Their first argument can be any predicate so that

(some 'pred list)

will return the first element of the list for which pred evaluates to t. Similarly for every. Also note that for Emacs Lisp it suffices to just quote the predicate function rather than using the #' that Common Lisp requires.

This entry was posted in Programming and tagged , . Bookmark the permalink.

3 Responses to Applying and And or In Emacs

  1. Phil says:

    Zach’s post says this is the case in Common Lisp because and is a macro. Emacs Lisp describes and as a “special form”, and discusses that in the manual at info node “(elisp) Special Forms”

    • jcs jcs says:

      That’s right. In any Lisp-like language and and or will be special because the arguments can’t be evaluated before it is executed. In Common Lisp and most (all?) Schemes they are macros. In Emacs Lisp they are C functions that work pretty much the way you would imagine they do. In either case apply won’t work so you have to use every or some.

  2. Paul Hobbs says:

    If you really want to use and, then you can do this:
    (apply (lambda (&rest args) (eval `(and ,@args))) '(1 2 3 nil))

    Of course, this is very unsafe.

Leave a Reply

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

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>