The less-familiar parts of Lisp for beginners — notany

Onward through our list of less familiar parts of common Lisp.  I had originally skipped every, but I think I’d like to bring it up, along with its related functions, just to point out something helpful.  The functions every, some, notevery, and notany may look redundant in the context of Lisp’s and and or, but they do have some uses by virtue of the fact that they are functions.

Macros are useful, but there are some places they cannot go.  You cannot pass a macro to mapcar, or funcall, or apply.  While that is inconvenient, the and and or macros of Lisp have the familiar short-circuiting behaviour of && and || in C++.  The notany function and its relatives are functions, and so do not short-circuit, all of their arguments are evaluated whether or not there is an intermediate result that conclusively establishes the return code.

The reason I bring this up is that newcomers might not have noticed the way these functions can be used in mapcar contexts and the like, to achieve the effect of determining, for instance, whether a list of forms are all true.  Let’s look at the and case:
 

CL-USER> (let ((num 10))
           (funcall 'and (numberp num) (> num 9)))
; Evaluation aborted on #<UNDEFINED-FUNCTION AND {1003E5B0F3}>.
CL-USER> (let ((num 10))
           (funcall 'every 'identity (list (numberp num) (> num 9))))
T

As you see, the funcall failed because and, being a macro, cannot be invoked in this manner.

Note that this example is only an example.  The particular way I’ve laid this out is for illustrative purposes, and if we were really intent on making this particular test, we would use ‘and as follows:
 

CL-USER> (let ((num 10))
           (and (numberp num)
                (> num 9)))
T

In fact, the example I give above with funcall and every would be wrong in real code, because both the numberp and the > operations would be evaluated up front, and if the variable num did not hold a number, then the comparison operator would error out.  This is only to show, in a simple context, how notany and its relatives, being functions, might be used in places where macros are illegal.

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=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.