# Obtaining head and parts without evaluation

I have been trying to write a routine MyHead and MyPart which would have the following properties.

MyHead[2+3]


evaluates to Plus

MyHead[(2+4)[10,11]]


evaluates to 2+4 (and not 6).

MyPart[f[2+3,10+11],1]


evaluates to 2+3

MyPart[f[2+3,10+11],2]


evaluates to 10+11

Ideally, this could be used to deeply dive into an expression. For example, it could find the local variables in the module

g[x_] := Module[{y,z,w},t];


from

Defintions[g]


I can't get it. Any suggestions?

Mark

You can capture but you can't return 2+4 unless you hold it somehow. I will use Hold for that purpose:

MyHead // Attributes = HoldAll;

MyPart // Attributes = HoldAll;
MyPart[expr_, spec__] := Hold[expr][[{1}, spec]]


It fits all your examples except it returns results wrapped with Hold. You can use HoldForm to not show it but the point holds.

I tend to prefer Defer over Hold because it doesn't show in the output and the results can be used as new input without having to release the hold manually.

Other than that, the following is copied straight from Kuba's solution:

MyHead // Attributes = HoldAll;
MyPart // Attributes = HoldAll;
MyPart[expr_, spec__] := Defer[expr][[{1}, spec]]