7

I defined a function f like

f[x___, y_] := something;

and if xs and y are all number, when I use this function, I would input like this:

f[1, 5, 3, 6, 3]

For this, x = Sequence[1, 5, 3, 6] and y = 3.

Suppose that I have a list l = {1, 5, 3, 6}. Then I might use f like

f[l /. List -> Sequence, 3]

using ReplaceAll to convert List to Sequence.

It is very good way to convert I think.

But, the problem is, when I want to input

f[1, {5, 3}, 6, 3]

which is given by l = {1, {5, 3}, 6}, if I use /., ReplaceAll, {5, 3} is also converted into the sequence so the whole input becomes f[1, 5, 3, 6, 3], not f[1, {5, 3}, 6, 3].

I have searched several alternative functions like Replace which includes a levelspec option. But Replace can not convert List.

How can I convert without loss of inside lists?

Analysis
  • 369
  • 1
  • 7

3 Answers3

10
l = {1, {5, 3}, 6}

Then use:

f[Sequence @@ l, 3]

f[1, {5, 3}, 6, 3]

RunnyKine
  • 33,088
  • 3
  • 109
  • 176
8

Sequence @@ is probably the "right" way to do this for normal functions, but you should know that you can also use SlotSequence or BlankSequence in Function or replacement respectively:

l = {1, {5, 3}, 6}

f[##, 3] & @@ l
f[1, {5, 3}, 6, 3]
l /. _[x__] :> f[x, 3]
f[1, {5, 3}, 6, 3]

These become important in the case where f holds its arguments:

SetAttributes[f, HoldAll]

f[Sequence @@ l, 3]
f[##, 3] & @@ l
l /. _[x__] :> f[x, 3]
f[Sequence @@ l, 3]

f[1, {5, 3}, 6, 3]

f[1, {5, 3}, 6, 3]

Note that Sequence @@ l does not evaluate.

Further distinction is apparent between the second two methods when the input is to be held:

l = Hold[1 + 1, {5!, 3/0}, 6 - 1];

This causes evaluation because the Function was not also given the HoldAll attribute:

f[##, 3] & @@ l

During evaluation of In[22]:= Power::infy: Infinite expression 1/0 encountered. >>

f[2, {120, ComplexInfinity}, 5, 3]

This does not:

l /. _[x__] :> f[x, 3]
f[1 + 1, {5!, 3/0}, 6 - 1, 3]

Reference: Injecting a sequence of expressions into a held expression

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
4

If it is just a matter of replacing the first List, then this could work also:

l = {1, {5, 3}, 6};
f[Delete[l, 0], 3]

(*f[1, {5, 3}, 6, 3]*)
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78