pythoncommon-lisppython-itertoolsstarmap

Common Lisp equivalent of Python's itertools.starmap?


Python's Itertools has what is called starmap. Given a collection of collections and a function, it applies the function to each collection strictly inside the collection, using the elements of said internal collection as arguments to the function. For example,

from itertools import starmap
 
NestedList = [(1, 2), (3, 4), (5, 6), (0, 0), (1, 1), (2, 2)]

list(starmap(lambda x, y:x + y, NestedList))

returns the list containing 3, 7, 11, 0, 2, and 4.

I refuse to believe that Python was the first to come up with this concept, but I'm drawing a blank when I try to think of what it was called in older languages. Does any analogous functionality exist in common lisp? I feel certain that it does, but I cannot name it.


Solution

  • Use a combination of mapcar and apply:

    (defun starmap (f list)
      (mapcar (lambda (x) (apply f x)) list))
    

    Or loop with the keyword collect:

    (defun starmap (f list)
      (loop for x in list 
            collect (apply f x)))
    

    Examples:

    > (starmap (lambda (x y) (+ x y)) '((1 2) (3 4) (5 6) (0 0) (1 1) (2 2)))
    (3 7 11 0 2 4)
    
    > (starmap #'expt '((1 2) (3 4) (5 6) (0 0) (1 1) (2 2)))
    (1 81 15625 1 1 4)