Passing a list of functions as an argument in common Lisp -


say there function f. want pass list of functions argument function f.

function f go through each function in list 1 one , apply each 1 2 integers: x , y respectively.

for example, if list = (plus, minus, plus, divide, times, plus) , x = 6 , y = 2, output this:

8 4 8 3 12 8 

how implement in common lisp?

there 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 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 on.

the first 2 readable, third 1 how rookie in first lisp course it, fourth 1 still rookie, after heard tail call optimization, fifth 1 written under cover haskeller.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -