Mathematica Asked on July 9, 2021
For some function f, consider the following expression:
f[2] f[5] - f[1] f[2] f[5] - f[2] f[3] f[5] + f[1] f[2] f[3] f[5] - f[2] f[4] f[5] + f[1] f[2] f[4] f[5] + f[2] f[3] f[4] f[5] - f[1] f[2] f[3] f[4] f[5]
How can I manipulate this expression so that it instead reads:
f[2,5] - f[1,2,5] - f[2,3,5] + f[1,2,3,5] - f[2,4,5] + f[1,2,4,5] + f[2,3,4,5] - f[1,2,3,4,5]
I.e. the function is now implemented on a list of the individual arguments. I’ve had a go at trying Map
to achieve this but with no luck.
EDIT TO QUESTION
To make this more meaningful for functions, how can the above string be passed as a single vector. Specifically, how can we obtain the output
f[{2,5}] - f[{1,2,5}] - f[{2,3,5}] + f[{1,2,3,5}] - f[{2,4,5}] + f[{1,2,4,5}] + f[{2,3,4,5}] - f[{1,2,3,4,5}],
this form can then be applied to a predefined function f[u]
that operates on the list u
. The function should also be able to take additional arguments.
Try using upvalues:
Times[f[x__], f[y__]] ^:= f[x, y]
and then evaluating the expression f[2] f[5] - f[1] f[2] f[5] - ...
again.
You could also do it without modifying f
and using ReplaceRepeated
(//.
):
expr //. Times[f[x__], f[y__]] :> f[x, y]
Correct answer by thorimur on July 9, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP