简体   繁体   English

在Lisp中传递函数列表作为参数

[英]Passing a list of functions as an argument in common Lisp

Say there is a function F. I want to pass a list of functions as an argument into function F. 假设有一个函数F。我想将函数列表作为参数传递给函数F。

Function F would go through each function in the list one by one and apply each one to two integers: x and y respectively. 函数F会逐一遍历列表中的每个函数,并将每个函数分别应用于两个整数:x和y。

For example, if the list = (plus, minus, plus, divide, times, plus) and x = 6 and y = 2 , the output would look like this: 例如,如果list =(加,减,加,除, x = 6 ,加)且x = 6y = 2 ,则输出将如下所示:

8 4 8 3 12 8

How do I implement this in common Lisp? 如何在常见的Lisp中实现此功能?

There are many possibilities. 有很多可能性。

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)

And so on. 等等。

The first two are readable, the third one is probably how a rookie in a first Lisp course would do it, the fourth one is still the rookie, after he heard about tail call optimization, the fifth one is written by an under cover Haskeller. 前两个是可读的,第三个可能是Lisp的第一门课程中的菜鸟如何做,第四个仍然是菜鸟,在他听说了尾部调用优化之后,第五个是由隐藏的Haskeller编写的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM