2013-04-20 104 views
0

争论说有一个功能F.我想传递的函数列表作为参数进入函数F传递函数列表中的Common Lisp

函数f会经历各功能列表一个接一个地将每一个应用到两个整数:x和y。

例如,如果列表=(加,减,加,除,时间,加号)和x = 6y = 2,输出应该是这样的:

8 4 8 3 12 8 

如何共同实现这个Lisp的?

回答

5

有很多可能性。

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课程中的新手如何做到的,第四个仍然是新手,在听到尾部呼叫优化之后,第五个是由在Haskeller掩护下。

+1

谢谢。非常感谢您的回答。 – 2013-04-20 05:01:58

+0

不客气。如果你想接受答案,你可以点击答案左边的空心箭头。另外,请注意,您可以使用'if'而不是'cond' - 这或多或少是通过反射写的。 – danlei 2013-04-20 05:04:13