将函数列表作为参数传递给Common Lisp

mar*_*nny 1 lisp function list

假设有一个函数F.我想将一个函数列表作为参数传递给函数F.

函数F将逐个遍历列表中的每个函数,并将每个函数分别应用于两个整数:x和y.

例如,如果list =(plus,minus,plus,divide,times,plus)x = 6y = 2,输出将如下所示:

8 4 8 3 12 8
Run Code Online (Sandbox Code Playgroud)

我如何在常见的Lisp中实现它?

dan*_*lei 6

有很多种可能性.

CL-USER> (defun f (x y functions)
           (mapcar (lambda (function) (funcall function x y)) functions))
F
CL-USER> (f 6 2 (list #'+ #'- #'+ #'/ #'* #'+))
(8 4 8 3 12 8)
CL-USER> (defun f (x y functions)
           (loop for function in functions
                 collect (funcall function x y)))
F
CL-USER> (f 6 2 (list #'+ #'- #'+ #'/ #'* #'+))
(8 4 8 3 12 8)
CL-USER> (defun f (x y functions)
           (cond ((null functions) '())
                 (t (cons (funcall (car functions) x y)
                          (f x y (cdr functions))))))
F
CL-USER> (f 6 2 (list #'+ #'- #'+ #'/ #'* #'+))
(8 4 8 3 12 8)
CL-USER> (defun f (x y functions)
           (labels ((rec (functions acc)
                      (cond ((null functions) acc)
                            (t (rec (cdr functions)
                                    (cons (funcall (car functions) x y)
                                          acc))))))
             (nreverse (rec functions (list)))))
F
CL-USER> (f 6 2 (list #'+ #'- #'+ #'/ #'* #'+))
(8 4 8 3 12 8)
CL-USER> (defun f (x y functions)
           (flet ((stepper (function result)
                    (cons (funcall function x y) result)))
             (reduce #'stepper functions :from-end t :initial-value '())))
F
CL-USER> (f 6 2 (list #'+ #'- #'+ #'/ #'* #'+))
(8 4 8 3 12 8)
Run Code Online (Sandbox Code Playgroud)

等等.

前两个是可读的,第三个可能是第一个Lisp课程中的新手如何做到的,第四个仍然是新手,在听说尾部调用优化后,第五个是由封底的Haskeller编写的.