Search code examples
lispcommon-lisp

How to dissolve or splice a list in common lisp?


Let's say I have a function Foo that takes 3 arguments. Foo for example sums these 3 numbers.

(defun Foo (a b c) 
  (+ a b c)

Then I have have a list of these 3 values. Is there a way of dissolving this list, so each value gets bind to the parameter?

(setf list (list 1 2 3))
> (1 2 3)
(Foo (dissolve list))
> 6

Only option I came up with was using macros, but then I got error such that ,@ cannot be right after backquote.

(defmacro dissolve (list)
  `,@list)

I know, one of the answers is to use &rest inside Foo function, but I don't want to. I am just wondering whether there is such a construct that fixes this from outside of the function.


Solution

  • Yes, it is called apply:

    (apply #'+ '(1 2 3))
    => 6
    

    What you are asking for, (Foo (dissolve list)), is impossible because of the evaluation rules of Lisp: Foo is a function and your form passes is exactly one argument.