Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating only particular Head type in expression?

I remember seeing a recipe to take an expression and evaluate every Head that matches pattern x, while leaving subexpressions with non-matching heads unevaluated. I can't find this recipe anymore, does anyone know the right way to do this?

like image 858
Yaroslav Bulatov Avatar asked Nov 22 '10 22:11

Yaroslav Bulatov


1 Answers

This one is from Ted Ersek's Mathematica Tricks under "Clever Little Programs".
Thanks to @TomD for the pointer.

EvaluatePattern[expr_,pattn_]:=expr/.Pattern[p, pattn]:>With[{eval=p},eval/;True]

In[368]:= test = HoldForm[7 (1 + 2 - 2^2) (8 + 8)];
          EvaluatePattern[test, _Plus] //InputForm

Out[369]= HoldForm[7*-1*16]  

Edit

It seems to work also with Hold[], but I never ran a deep test.

like image 120
Dr. belisarius Avatar answered Sep 24 '22 23:09

Dr. belisarius