1
$\begingroup$

I would expect this

F[x_] := Module[{aux = x},    aux = X]; 
{a + b + c, e+ f} // Map[Distribute@*F]

to yield

{3X, 2X}

instead, the function is not distributed over plus, yielding

{X, X}

Clearing F, Clear[F], I get what I expected

{F[a]+F[b]+F[c],F[d]+F[e]}

How to distribute the function before evaluating it?

$\endgroup$

1 Answer 1

3
$\begingroup$
Clear[F];
F[x_] := X;
{a + b + c, e + f} // Map[Distribute@*Hold[F]] // ReleaseHold
(* {3 X, 2 X} *)

Clear[F];
F[x : Except[_Plus]] := X;
{a + b + c, e + f} // Map[Distribute@*F]
(* {3 X, 2 X} *)

Clear[F];
F[x_ /; Head[x] =!= Plus] := X;
{a + b + c, e + f} // Map[Distribute@*F]
(* {3 X, 2 X} *)
$\endgroup$
5
  • $\begingroup$ Thank you for the three (!) alternatives. Do you know why if F[x_]:=x^2 the Hold is not needed? $\endgroup$
    – Albercoc
    Commented Mar 31, 2023 at 14:15
  • $\begingroup$ Do you mean F[x_] := x^2 or F[x_] := X^2? $\endgroup$
    – Domen
    Commented Mar 31, 2023 at 14:32
  • $\begingroup$ Small case. When it actually uses the argument F[x_]:=x^2 $\endgroup$
    – Albercoc
    Commented Mar 31, 2023 at 14:47
  • $\begingroup$ Because in that case, it is not F that is getting distributed itself, but Power (^2). Compare the following evaluation traces. $\endgroup$
    – Domen
    Commented Mar 31, 2023 at 15:30
  • $\begingroup$ Great thank you. I didn't know about Trace. So useful! $\endgroup$
    – Albercoc
    Commented Mar 31, 2023 at 15:45

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.