# Find all the subexpressions with a given head in an expression

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)/(h + c) + h;
findAll[expr, h]


{h, h, h}

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

DeleteDuplicates @ Cases[expr, _h, Infinity]


{h, h, h}

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

findAll[expr, h]


{h, h, h}

• 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. – Kagaratsch May 1 '18 at 0:10
• @Kagaratsch, use Alternatives instead of Or, i.e., try DeleteDuplicates @ Cases[expr, _h1 | _h2, Infinity] – kglr May 1 '18 at 0:11
• I see, thank you again! – Kagaratsch May 1 '18 at 0:12
• @Kagaratsch, my pleasure. Thank you for the accept. – kglr May 1 '18 at 0:13
• @Kagaratsch, try the pattern _h[_]? – kglr Jun 24 '19 at 23:36