Obtaining head and parts without evaluation
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;
MyHead[expr_] := MyPart[expr, 0]
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;
MyHead[expr_] := MyPart[expr, 0]
MyPart // Attributes = HoldAll;
MyPart[expr_, spec__] := Defer[expr][[{1}, spec]]
MyHead[2 + 3]
(* Plus *)
MyHead[(2 + 4)[10, 11]]
(* 2 + 4 *)
MyPart[f[2 + 3, 10 + 11], 1]
(* 2 + 3 *)
MyPart[f[2 + 3, 10 + 11], 2]
(* 10 + 11 *)