17

In Python, assuming the following function is defined:

def function(a, b, c):
    ... do stuff with a, b, c ...

I am able to use the function using Python's sequence unpacking:

arguments = (1, 2, 3)
function(*arguments)

Does similar functionality exist in Common Lisp? So that if I have a function:

(defun function (a b c)
    ... do stuff with a, b, c ...

And if I have a list of 3 elements, I could easily use those 3 elements as parameters to the function?

The way I currently implement it is the following:

(destructuring-bind (a b c) (1 2 3)
    (function a b c))

Is there a better way?

brildum
  • 1,759
  • 2
  • 15
  • 22
  • 1
    Note that there is `,@` which is similar. For example, `(let ((x '(2 3))) \`(1 ,@x 4 5))` becomes `(1 2 3 4 5)`. – xdavidliu Dec 25 '19 at 01:20

2 Answers2

23

Use the apply function:

(apply #'function arguments)

Example:

CL-USER> (apply #'(lambda (a b c) (+ a b c)) '(1 2 3))
6   
TrakJohnson
  • 1,755
  • 2
  • 18
  • 31
nominolo
  • 5,085
  • 2
  • 25
  • 31
11

apply

Katriel
  • 120,462
  • 19
  • 136
  • 170
  • 1
    Note that this only works when the function's only arguments are contained in the list. Otherwise, `destructuring-bind` is needed, and matches python's ability to do `function(*args, another_arg)`. – Mark Dec 09 '16 at 15:41