5

I'd like /@ instead of Table or Map. But let we have it inside pure function:

{#1, (#1 + #) & /@ #2} &[a, {b, c, d, e, ...}]

It is assumed that the second #1 should be the same as first - a first argument of a main function. So output should be:

{a, {a + b, a + c, ...}}

But of course according to the rules of Wolfram Language the second #1 stands for first argument of inner function, so output is:

{a, {2 b, 2 c, 2 d, ...}}

Is it possible to avoid Table in this case?

Clarification

In documentation there is an example: Horner nested polinomial:

Fold[x #1 + #2 &, 0, {a, b, c, d, e}]

I need a pure function instead of function of x, and short (for code-golf challenges). The ways suggested in the answers are not suitable in this case.

lesobrod
  • 1,657
  • 9
  • 14

2 Answers2

7

Plus is Listable:

{#1, #1 + #2} &[a, {b, c}]

But more generally, you can always use the full, explicit form of Function:

{#1, Function[x, #1 + x] /@ #2} &[a, {b, c}]

Or

Function[{addend, list}, {addend, Function[x, addend + x] /@ list}][a, {b, c}]

Some alternates to represent the case where the function we're mapping is non-Listable.

{#1, Thread[f[#1, #2]]} &[a, {b, c, d, e}]
(*{a,{f[a,b],f[a,c],f[a,d],f[a,e]}}*)

{#1, Function[x, f[#1, x], Listable][#2]} &[a, {b, c, d, e}] ({a,{f[a,b],f[a,c],f[a,d],f[a,e]}})

lericr
  • 27,668
  • 1
  • 18
  • 64
  • But what if we have big list, or/and non-listable operator? – lesobrod Jan 28 '23 at 15:21
  • The length of the list shouldn't matter. If the operator isn't listable, you can use the Function[...] form (I updated the answer) or you can actually set attributes of a Function (so write the Function as just appling the operator you want, but add a third argument of Listable). – lericr Jan 28 '23 at 15:26
  • Thread might work here as well for non-listable operators. – lericr Jan 28 '23 at 15:35
  • Don't forget there's also the Function shorthand ({x, y} |-> {x, f[x, #] & /@ y})[a, {b, c}] – flinty Jan 29 '23 at 13:04
3

It seems ReplaceAll is suitable for all cases:

{x, (x + #) & /@ #2} /. x -> #1 &[a, {b, c, d, e}]

Output: {a, {a + b, a + c, a + d, a + e}}

f = Fold[x #1 + #2 &, 0, {a, b, c, d}] /. x -> # &;
f@2

Output: 2 (2 (2 a + b) + c) + d

lesobrod
  • 1,657
  • 9
  • 14