Splicing a list of arguments into a function with Sequence

Sequence means more or less "no head". What you want to do is to remove the head List from an inner list. Or, put in another way, you want to replace this head with "no head". The operation that changes one head to another is Apply. Therefore, what you really want is

f[a, b, c, d, Sequence @@ array]

where @@ stands for Apply.


You can certainly bypass the use of Sequence[] (though it is certainly a neat thing):

f[a, b, c, d, ##] & @@ array
   f[a, b, c, d, e, f]

For completeness, neither of the existing answers will work as written when working with held expressions. That case is addressed in:

  • Injecting a sequence of expressions into a held expression

The most concise solution I know is what I have come to call the "injector pattern" in reference to that Q&A, for lack of another term.

Let's say our function is foo and we want to insert arguments from seq.

SetAttributes[foo, HoldAll];

seq = Hold[1/0, 8/4];

seq /. _[x__] :> foo[1, 2, x]
foo[1, 2, 1/0, 8/4]

Compare this to the result of the other two methods shown:

foo[1, 2, Sequence @@ seq]
foo[1, 2, Sequence @@ seq]
foo[1, 2, ##] & @@ seq

Power::infy: Infinite expression 1/0 encountered. >>

foo[1, 2, ComplexInfinity, 2]

The SlotSequence method can be adapted by giving the anonymous function a HoldAll attribute but this requires the use of an undocumented form:

Function[, foo[1, 2, ##], HoldAll] @@ seq
foo[1, 2, 1/0, 8/4]

Reference:

  • Pure function with attributes of arbitrary number of arguments: Is it possible?

Tags:

Syntax

Faq