5
$\begingroup$

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

$\endgroup$
0

2 Answers 2

7
$\begingroup$

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.

$\endgroup$
5
$\begingroup$

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    *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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