Here is a related question, but not quite what I'm after.

I would like to define a function f[x_] that has the distributive attribute, such that:



Of course I could do


but I suspect that this would be much slower than an actual Attribute. Unfortunately, I cannot find Distributive in the list of allowed attributes.

How should one define such a property to make sure that it performs as efficiently as possible?

  • 1
    $\begingroup$ Do you know about Distribute? e.g. Distribute[f[a + b + c]] $\endgroup$ Feb 14, 2018 at 22:59
  • $\begingroup$ @MikeHoneychurch wow, thank you! Good to know! $\endgroup$
    – Kagaratsch
    Feb 14, 2018 at 23:31

1 Answer 1

f[x__Plus] := Plus @@ (f /@ (List @@ x))

This is also about the same speed as:

f[x__Plus] := Map[f, x]

Which is also about the same speed as:

f[x__Plus] := Distribute[Unevaluated[f[x]]]

You can test the efficiency of this like so:

var = Sum[a[i], {i, 1, 100000}];

I am reasonably sure there isn't an attribute based solution, and I believe that most of the built-in functions that aren't coded in C rely on pattern matching to manage the distributive property. The trick here is to avoid relying on pattern matching more often than necessary: this splits out every summand in a single replacement.


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.