3

Say I have a function f of three parameters and a list l = {b,c}. I want to pass the first parameter to f manually, and use l for the other two. I can use Apply like this:

f[a, #1, #2]& @@ l

Is there a shorter expression, similar to how in Python I would just do f(a, *l)? Ideally I wouldn't have to specify the number of parameters (for convenience, mostly).

Of course the version with Apply works - I'm just interested to see if there's a neater version. The equivalent Python has the advantage that l appears inside the function where it should be, making it easier to read.

Javier
  • 285
  • 1
  • 5
  • 1
    f[a, Sequence @@ l] is what you are probably after. – Leonid Shifrin Mar 11 '21 at 13:44
  • 2
    @Leonid it sure does, thank you! – Javier Mar 11 '21 at 14:08
  • Glad it helped. – Leonid Shifrin Mar 11 '21 at 19:43
  • 1
    There is one caveat however, which is not discussed in the linked question. If your function f happens to have Hold attributes (in your case, HoldRest or HoldAll), then in general f[a, #1, #2]& @@ l and f[a, Sequence @@ l] are not equivalent, and in some cases you will find the former working while the latter not. For example, ClearAll[f]; SetAttributes[f, HoldRest]; f[x_, rest___Integer] := Plus[x, rest]. This will work fine when user as e.g. f[1, #1, #2]& @@ {2, 3}, but it will not evaluate when used as f[1, Sequence @@ {2, 3}]. – Leonid Shifrin Mar 11 '21 at 19:46

1 Answers1

1

Conversion of @Leonid Shifrin's comments into a community wiki answer:

Leonid Shifrin:

f[a, Sequence @@ l] is what you are probably after.

Does this answer your question? Splicing a list of arguments into a function with Sequence

There is one caveat however, which is not discussed in the linked question. If your function f happens to have Hold attributes (in your case, HoldRest or HoldAll), then in general f[a, #1, #2]& @@ l and f[a, Sequence @@ l] are not equivalent, and in some cases you will find the former working while the latter not. For example, ClearAll[f]; SetAttributes[f, HoldRest]; f[x_, rest___Integer] := Plus[x, rest]. This will work fine when used as e.g. f[1, #1, #2]& @@ {2, 3}, but it will not evaluate when used as f[1, Sequence @@ {2, 3}].

thorimur
  • 9,010
  • 18
  • 32