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


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

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

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]}

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