I am a very novice Mathematica user and still can't get my head around its evaluation control, all possible constructs related to it (e.g. Hold
, Unevaluated
, etc.) and how they work, despite the thorough documentation and the numerous StackExchange and StackOverflow questions discussing this topic. So, apologies for any possible duplicates.
My use case is the following: I have a function (say f
) defined by thousands of rules and patterns (DownValues
). I want to start from an unrolled representation of f[expr]
(for some expr
) and get the result of applying a single, particular rule to f[expr]
. I want the result to stay unrolled as well.
As a particular example, suppose we have the following:
In[1]: nat[0] := 0
In[2]: nat[n_] := 1 + nat[n - 1]
In[3]: DownValues[nat]
Out[3]: {HoldPattern[nat[0]] :> 0, HoldPattern[nat[n_]] :> 1 + nat[n - 1]}
In[4]: nat[10]
Out[4]: 10
Now, I want to start from an expression represented as nat[10]
(unevaluated!) and want to specifically apply the second rule (HoldPattern[nat[n_]] :> 1 + nat[n - 1]
) to obtain the expression in the form of 1 + nat[9]
. Analogously, shall I wish to apply the first rule (HoldPattern[nat[0]] :> 0
), I would expect the result to stay unchanged in its original form, i.e. nat[10]
.
Thank you for your help!
HoldForm[nat[10]] /. DownValues[nat][[2]]
./.
acts on all parts of the expression, but all of those parts are within aHoldForm
, so they don't evaluate any further. (Note thatHoldForm
is the same asHold
, with the only difference being how it prints in the output cell.) But, this has the unpleasant effect of not evaluating anything else in the expression, e.g.10 - 1
. To only hold occurrences ofnat
in an expression sounds like a good exercise! There are many ways to do that, but if you're stuck I can keep trying to help. $\endgroup$