3
$\begingroup$

I am using the following two lines of code relatively frequently

f/:Plus[f[x_], f[y_], z___]:=f[x+y]+z
f/:Times[c_, f[x_]]:=f[c x]

and I was wondering if it is possible to automate the process.

What I have in mind, is to supply a list of heads to a function and the function will make definitions similar to those presented above, for every head in the list.

The idea is to have a package that defines a bunch of heads that behave like f above and exports them to the user without having to show the user how the behavior is implemented.

I'm interested in avoiding possible side-effects from the automation process, if there are any.

So, to sum up, is it possible to automate the two TagSetDelayed definitions presented above, in a package that safely exports the heads exhibiting the same behaviour as f, without major side-effects?

$\endgroup$

1 Answer 1

5
+100
$\begingroup$

You mean something like:

Scan[
  Function[head,
    head /: Plus[head[x_], head[y_], z___] := head[x + y] + z;
    head /: Times[c_, head[x_]] := head[c x]
  ],
  {f, g, h}
]
$\endgroup$
2
  • $\begingroup$ if it works in a package without any weird side effects, sure it does $\endgroup$
    – joka
    Nov 14, 2020 at 19:41
  • 3
    $\begingroup$ @joka I use it myself quite regularly. Here, for example. $\endgroup$ Nov 14, 2020 at 23:15

Your Answer

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

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