5
$\begingroup$

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.

$\endgroup$
2

2 Answers 2

7
$\begingroup$

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]}}*)
$\endgroup$
4
  • $\begingroup$ But what if we have big list, or/and non-listable operator? $\endgroup$
    – lesobrod
    Commented Jan 28, 2023 at 15:21
  • $\begingroup$ 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). $\endgroup$
    – lericr
    Commented Jan 28, 2023 at 15:26
  • $\begingroup$ Thread might work here as well for non-listable operators. $\endgroup$
    – lericr
    Commented Jan 28, 2023 at 15:35
  • $\begingroup$ Don't forget there's also the Function shorthand ({x, y} |-> {x, f[x, #] & /@ y})[a, {b, c}] $\endgroup$
    – flinty
    Commented Jan 29, 2023 at 13:04
3
$\begingroup$

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

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.