【问题标题】:Passing a list of functions as an argument in common Lisp在通用 Lisp 中将函数列表作为参数传递
【发布时间】:2013-04-20 04:32:22
【问题描述】:

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

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

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

8 4 8 3 12 8

如何在普通的 Lisp 中实现这一点?

【问题讨论】:

    标签: list function lisp


    【解决方案1】:

    有很多可能性。

    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课程的菜鸟怎么做的,第四个还是菜鸟,听说尾调用优化后,第五个是一个under写的覆盖 Haskeller。

    【讨论】:

    • 谢谢。非常感谢您的回答。
    • 不客气。如果您想接受答案,可以单击答案左侧的空心箭头。另外,请注意,您可以使用 if 代替 cond - 这或多或少是由 reflex 编写的。
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多