list - 在 common Lisp 中将函数列表作为参数传递

标签 list function lisp

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

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

例如,如果列表 = (plus, minus, plus, divide, times, plus) and x = 6 and y = 2,输出看起来像这样:

8 4 8 3 12 8

我如何在通用 Lisp 中实现它?

最佳答案

有很多可能性。

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)

等等。

前两个是可读的,第三个大概是初学Lisp类(class)的菜鸟会怎么做,第四个还是菜鸟,听说tail call optimization后,第五个是under写的涵盖 Haskeller。

关于list - 在 common Lisp 中将函数列表作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16116590/

相关文章:

java - 从具有匹配名称的 List<Student> 中获取 Student 对象而不进行迭代 (Java)

c - 替代#define 以获得 C 中的灵活性

list - 如何将函数应用于列表的两个元素 - Haskell

r - 删除列表中数据框中的一列

javascript - 这个函数式 Javascript 示例如何工作?

c++ "error: no matching function for call to"在集合中计数时

variables - 理解 Lisp 中变量重新分配的困难

从 Javascript 到 Clojure

lambda - 为什么我的 lisp 代码给我...应该是一个 lambda 表达式?

python - 如何优雅地迭代列表或字典