Given a list of values, I want to reduce the list to T if all the elements are not NIL, NIL if not. This gives me an error:
(apply #'and (get-some-list))
As does this:
(reduce #'and (get-some-list))
This is the best I've come up with:
[11]> (defun my-and (x y) (and x y))
MY-AND
[12]> (reduce #'my-and '(T T T T T))
T
[13]> (reduce #'my-and '(T T T T NIL))
NIL
Why is "#'and" invalid? Is there a more idiomatic way to do this in Common Lisp?
You can use the 'sharp-quote' symbol only with ordinary functions.
COMMON LISP: A Gentle Introduction to Symbolic Computation, page 202
#'and
is invalid becauseand
is a macro, not a function.You can get around having to define a named function, by using a lambda:
There's no shortcut like
#'
though.Alternatively you can also use
every
with the identify function as the predicate.You can use the EVERY function:
and
Probably the most efficient way is using LOOP:
The advantage is that no function calls over the list elements are needed.
#'
is a read macro that expands into FUNCTION during read the expression. So#'and
is (FUNCTION AND).FUNCTION is described here: http://www.lispworks.com/documentation/HyperSpec/Body/s_fn.htm
FUNCTION takes a function name or a lambda expression and returns the corresponding function object.
AND is defined here: http://www.lispworks.com/documentation/HyperSpec/Body/m_and.htm
It says that AND is a macro, not a function. The consequence is that (FUNCTION AND) does not work, since FUNCTION needs a function and not a macro to return the corresponding function object. As sepp2k describes in his answer, you can create a function using LAMBDA and use the macro AND inside that function. Macros cannot be passed as values and later be called via FUNCALL or APPLY. This works only with functions.
This solution is written as
LAMBDA is a macro that expands
(lambda (...) ...)
into(function (lambda (...) ...))
.So above is really:
which can be written as
FUNCTION is needed because Common Lisp makes a difference between the namespace for values and functions. REDUCE needs to get the function passed as an argument by value. So we need to retrieve the function from the function namespace -- which is the purpose of FUNCTION. Whenever we want to pass a function object, we need to get it from the function namespace.
For example in the case of a local function:
LAMBDA as a convenience macro that expands into (FUNCTION (LAMBDA ...)) has been added during the design of Common Lisp.