1
$\begingroup$

Given an arbitrary mathematical expression expr involving summations and multiplications I would like to find all unique instances of subexpressions with a specified head, e.g., the head h. I hacked together a solution as follows:

findAll[expr_, h_] := 
  Cases[expr /. Times -> list1 /. Plus -> list2 /. h[x__] :> (h[x] /. list2 -> Plus /. list1 -> Times) /. list1 -> List /. list2 -> List /. Power -> List // Flatten, h[__]] // DeleteDuplicates

but I'm afraid my code is ignoring some advanced functionality that might be present in Mathematica and could return a result much quicker. What would be an efficient way to write my code?

Example:

expr = (a + b h[1])/(h[2] + c) + h[3];
findAll[expr, h]

{h[3], h[1], h[2]}

$\endgroup$
  • 2
    $\begingroup$ DeleteDuplicates@Cases[expr, _h, Infinity]? $\endgroup$ – kglr Apr 30 '18 at 23:55
  • $\begingroup$ @kglr wow, thanks! This seems to be it. $\endgroup$ – Kagaratsch Apr 30 '18 at 23:57
5
$\begingroup$
DeleteDuplicates @ Cases[expr, _h, Infinity]

{h[1], h[2], h[3]}

ClearAll[findAll]
findAll = DeleteDuplicates @ Cases[#, Blank[#2], Infinity] &;

findAll[expr, h]

{h[1], h[2], h[3]}

$\endgroup$
  • $\begingroup$ Sorry to ask for more details, but what if I'm interested in finding symbols with several heads in one go, how should I do that properly? I tried DeleteDuplicates @ Cases[expr, _h1||_h2, Infinity], but it does not work. $\endgroup$ – Kagaratsch May 1 '18 at 0:10
  • 1
    $\begingroup$ @Kagaratsch, use Alternatives instead of Or, i.e., try DeleteDuplicates @ Cases[expr, _h1 | _h2, Infinity] $\endgroup$ – kglr May 1 '18 at 0:11
  • $\begingroup$ I see, thank you again! $\endgroup$ – Kagaratsch May 1 '18 at 0:12
  • $\begingroup$ @Kagaratsch, my pleasure. Thank you for the accept. $\endgroup$ – kglr May 1 '18 at 0:13
  • 1
    $\begingroup$ @Kagaratsch, try the pattern _h[_]? $\endgroup$ – kglr Jun 24 '19 at 23:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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