I need to write a function in lisp with two arguments – list of argumentless functions and list of integers.
I need to evaluate functions from first list in order given by a second, i.e. (fun ‘(#’a #’b #’c) ‘(2 0 1)) should evaluate c, a, b.
I tried such function:
(defun z4(funs kols)
(funcall (nth (first kols) funs))
(z4 funs (rest kols))
)
but in funcall I am geting error
NIL is not of type CONS.
What does it means? I am getting same error by calling simply
(funcall (first funs))
so I assume it is something with with getting function from the list of functions. How can I evaluate function get from list of functions?
With each recursive call you reduce the
kolsparameter untill it becomesnil. Whenkolsbecomesnilyou should terminate the recursion, so you should add the test for the terminating condition (i.e., for empty list):I suggest a more readable solution (it’s also more preferrable since ANSI Common Lisp Standard doesn’t force implementations to perform tail call optimization):
In the previous examples I assume that you run your functions for their side effects, not for the return values.
Edit 1
As Vatine noted, using
nthand lists to provide a collection with random access is not good for the performance, so it might be worth to store functions in avector(that is a one-dimensionalarray) rathen than in a list. So, assuming thatfuncsis avectorof functions, the function can be defined as follows:Moreover, we can replace
arefwithsvrefif the array of functions is asimple vector(glossary entry). The former is more general, but the latter may be faster in some implementations.One can create a
simple vectorof functions using eitheror
A
simple vectorof functions can be created using themake-arrayfunction as well, but only if:adjustableand:fill-pointerkeyword arguments are unspecified ornil.