Calling a List of Functions in Common Lisp
In Clojure, I can define a sequence of functions and then call them as they were any other value, like so:
(doseq [op [+ - * /]] (println (op 1 2 3 4)))
which produces the following output:
10
-8
24
1/24
nil
Trying to do the same in Common Lisp only results in an error:
(dolist (op '(+ - * /)) (print (op 1 2 3 4)) ; in: DOLIST (OP '(+ - * /)) ; (LET ((OP (TRULY-THE (MEMBER / * - +) (CAR #:N-LIST671)))) ; (SETQ #:N-LIST671 (CDR #:N-LIST671)) ; (TAGBODY (PRINT (OP 1 2 3 4)))) ; ; caught STYLE-WARNING: ; The variable OP is defined but never used. ; in: DOLIST (OP '(+ - * /)) ; (OP 1 2 3 4) ; ; caught STYLE-WARNING: ; undefined function: OP ; ; compilation unit finished ; Undefined function: ; OP ; caught 2 STYLE-WARNING conditions debugger invoked on a UNDEFINED-FUNCTION: The function COMMON-LISP-USER::OP is undefined. Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL. restarts (invokable by number or by possibly-abbreviated name): 0: [ABORT] Exit debugger, returning to top level. ("undefined function")
Calling op
both #'op
didn't work for me either.
So, is there a way to do this in CL?
source to share
Since the namespace for functions and the namespace for data are separated in LISP -2 (and therefore in common-lisp), you need to use funcall
when passing functions as parameters:
(dolist (op '(+ - * /)) (print (funcall op 1 2 3 4))))
funcall
the function is roughly equivalent to Clojure apply
and will apply the function op
to the provided parameters. In this case, one more thing happens as it op
is a symbol associated with a function, but funcall
will take care of that.
source to share