Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise Lisp code to apply a list of functions all to the same argument(s) and get a list of the return values?

Suppose I have a single element, and I have a list of predicates (functions). I want to apply each of these predicates to the single element and get a corresponding list of return values. I know that map and friends can apply a single function to each a list of arguments, but is there any concise syntax to apply many functions to a single argument?

Of course I can do

(mapcar (lambda (pred) (funcall pred SINGLE-ELEMENT)) LIST-OF-PREDICATES)

but it would be nice if there was a function that worked like:

(test-predicates-against-element LIST-OF-PREDICATES SINGLE-ELEMENT)

Obviously I can just defun it, but I wanted to know if there is an accepted method for doing this.

like image 500
Ryan C. Thompson Avatar asked Aug 03 '10 23:08

Ryan C. Thompson


1 Answers

This operation is not that common and there is not really a predefined way to do it, other than writing it directly, in Common Lisp. Various people like a short syntax and added syntactic elements that would help in such a case to all kinds of Lisps. In Common Lisp one might want to write a function that does what you want (instead of adding syntax).

(defun fmap (functions &rest args)
  (declare (dynamic-extent args))
  "Applies each function to the arguments. Returns a list of results."
  (mapcar (lambda (function)
            (apply function args))
          functions))

CL-USER 1 > (fmap (list #'+ #'- #'* #'/) 42 17)
(59 25 714 42/17)
like image 173
Rainer Joswig Avatar answered Oct 23 '22 10:10

Rainer Joswig