The main point of this question is the logic behind the operation of the first argument of TraceScan (as well as the associated fourth argument but that is not needed for the problem in question): it sometimes excludes some evaluation steps (which Trace with option TraceOriginal->True gives) but sometimes it includes them as demonstrated in the following examples. I am interested in understanding the logic behind this behavior and how to force TraceScan to give the full set of evaluation steps. This question originally arose in this thread (see my comments to the answer). The general comparison of the behavior of TraceScan as compared to that of Trace was given by WReach here but it does not answer the following questions:
1.) Why doesn't TraceScan give the final expression f[a,1] in this
case while Trace gives:
In[1]:= SetAttributes[traceScan,HoldAll];
traceScan[expr_]:=(list={};TraceScan[AppendTo[list,#]&,expr];list)
In[3]:= ClearAll[f,a];
Trace[f[a,1],TraceOriginal->True]
Out[4]= {f[a,1],{f},{a},{1},f[a,1]}
In[5]:= ClearAll[f,a];
traceScan[f[a,1]]
Out[6]= {f[a,1],f,a,1}
2.) And, in the following case, why do both Trace and TraceScan give the
final expression f[1,a] wheras only Trace gives the intermediate expression
f[a,1] which corresponds to the step of the evaluation before applying the Orderless attribute of f:
In[7]:= ClearAll[f,a];
SetAttributes[f,Orderless]
Trace[f[a,1],TraceOriginal->True]
Out[9]= {f[a,1],{f},{a},{1},f[a,1],f[1,a]}
In[12]:= ClearAll[f,a];
SetAttributes[f,Orderless]
traceScan[f[a,1]]
Out[14]= {f[a,1],f,a,1,f[1,a]}
3.) And why in this last case do both Trace and TraceScan give the final
expression ff[1,b] and the intermediate expression ff[b,1] which corresponds to the step of the evaluation before applying the Orderless attribute of ff:
In[21]:= ClearAll[f,ff,a];
SetAttributes[ff,Orderless];f=ff;a=b;
Trace[f[a,1],TraceOriginal->True]
Out[23]= {f[a,1],{f,ff},{a,b},{1},ff[b,1],ff[1,b]}
In[24]:= ClearAll[f,ff,a];
SetAttributes[ff,Orderless];f=ff;a=b;
traceScan[f[a,1]]
Out[26]= {f[a,1],f,ff,a,b,1,ff[b,1],ff[1,b]}
4.) Is there a way to force TraceScan to always give exhaustive
information about evaluation as Trace does?
In addition
Here is another, more informative version of traceScan which uses the fourth argument:
SetAttributes[traceScan, HoldAll];
traceScan[expr_] := (list1 = list2 = {};
TraceScan[AppendTo[list1, #] &, expr, _,
AppendTo[list2, {##}]&];
Column[{list1, list2}])
Cases 1 and 2. Citing the Documentation:
Normally, ... Trace intercepts expressions only after function
arguments have been evaluated. By setting TraceOriginal->True, you
can get Trace also to look at expressions before function
arguments have been evaluated.
It seems that setting TraceOriginal->True just results in prepending additional information to the default output of Trace. As the result, we see unnecessary additional "intermediate expression" f[a,1] which in really does not appear in the evaluation chains in both cases as it is shown by TraceScan and TracePrint:
In[1]:= ClearAll[f, a];
SetAttributes[f, Orderless]
TracePrint[f[a, 1]]
During evaluation of In[1]:= f[a,1]
During evaluation of In[1]:= f
During evaluation of In[1]:= a
During evaluation of In[1]:= 1
During evaluation of In[1]:= f[1,a]
Out[3]= f[1, a]
So it looks like a bug in Trace.
Case 3. In this case everything works as expected because the intermediate expression ff[b,1] indeed appears in the evaluation chain as the result of applying of the definition associated with f. Nothing unexpected.
Conclusion. Both Trace and TraceScan give exhaustive information about evaluation chain but the output generated by Trace can additionally contain misleading "intermediate expression" which is in fact just the initial expression of the chain.
Related
In preparing a response to An unexpected behavior of PatternTest in Mathematica I came across an unexpected Mathematica behavior of my own.
Please consider:
test = (Print[##]; False) &;
MatchQ[{1, 2, 3, 4, 5}, {x__?test, y__}]
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
False
Since, as Simon's quote of the documentation concisely states:
In a form such as __?test every element in the sequence matched by __
must yield True when test is applied.
I am wondering why Mathematica is testing the first element of the list four separate times. Of course there are four ways to make up the underlying pattern {x__, y__} and if this were a Condition test then all elements that make up the sequence x would need to be tested, but I don't think that is the case here.
Does the logic not hold that if the first element of the list fails PatternTest then given pattern cannot match?
If it does hold, why is Mathematica not making this simple optimization?
Borrowing an example from yoda's answer, here is another example of what appears to be excess evaluation:
In[1]:= test2 = (Print###; Positive###) &;
MatchQ[{1, 2, 3, 4, -5}, {x__?test2, y__?Negative}]
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
During evaluation of In[1]:= 2
During evaluation of In[1]:= 1
During evaluation of In[1]:= 2
During evaluation of In[1]:= 3
During evaluation of In[1]:= 1
During evaluation of In[1]:= 2
During evaluation of In[1]:= 3
During evaluation of In[1]:= 4
Out[2]= True
I admit to having never explored this aspect of pattern matching before, and I am disturbed by the seeming inefficiency of this. Is this really as bad as it looks, or is some kind of automatic caching taking place? Print appears to indicate against that.
Is there a more efficient pattern based way to write this?
Is this level of redundancy required for correct pattern matching behavior, and why?
I made a false assertion in haste, but I leave it because good answers below address it. Please ignore it in future answers.
It is easy to demonstrate that a similar optimization is made in other
cases:
MatchQ[{-1, 2, 3, 4, 5}, {__?Positive, y__?test}]
(Nothing is printed.)
False
Here Mathematica correctly never even tests any elements for y.
I think everyone is forgetting about the side effects that are possible in test functions. Here is what I think is happening: as Mr.Wizard and others mentioned, there are several ways the pattern may match, just combinatorially. For each combination of {x} and {y}, the x pattern is first tested. By the way, there is no point in defining functions of multiple arguments (##), since, as #Simon explained, the test function is applied separately to each element in the sequence. And this also explains why only the first element (-1) is printed: as soon as the first non-matching element is found, the pattern-matcher stops and goes on to test the next available combination.
Here is a more illustrative example:
In[20]:=
MatchQ[{-1,2,3,4,5},{_,x__?(Function[Print[#];Positive[#]])}]
During evaluation of In[20]:= 2
During evaluation of In[20]:= 3
During evaluation of In[20]:= 4
During evaluation of In[20]:= 5
Out[20]= True
Now it prints all of them, since the function is applied to them one by one, as it has to in this case.
Now to the crux of the matter. Here I set up a test function with a side effect, which decides to change its mind after it tests the very first element:
Module[{flag = False},
ClearAll[test3];
test3[x_] :=
With[{fl = flag},
If[! flag, flag = True];
Print[x];
fl
]
];
The first combination (which is {-1},{2,3,4,5} will be rejected since the function gives False at first. The second one ({-1,2},{3,4,5}) will be accepted however. And this is exactly what we observe:
In[22]:=
MatchQ[{-1,2,3,4,5},{x__?test3,y__}]
During evaluation of In[22]:= -1
During evaluation of In[22]:= -1
During evaluation of In[22]:= 2
Out[22]= True
The printing stopped as soon as the pattern-matcher found a match.
Now, from here it must be obvious that the optimization mentioned in the question and some other answers is not generally possible, since pattern-matcher has no control over the mutable state possibly present in the testing functions.
When thinking about the pattern-matching, we usually view it as a process separate from evaluation, which is largely true, since the pattern-matcher is a built-in component of the system which, once patterns and expressions evaluate, takes over and largely bypasses the main evaluation loop. There are however notable exceptions, which make the pattern-matching more powerful at the price of getting it entangled with the evaluator. These include the uses of Condition and PatternTest, since these two are the "entry points" of the main evaluation process into the otherwise isolated from it pattern-matching process. Once the pattern-matcher hits one of these, it invokes the main evaluator on the condition to be tested, and anything is possible then. Which brings me once again to the observation that the pattern-matcher is most efficient when tests using PatternTest and Condition are absent, and the patterns are completely syntactic - in that case, it can optimize.
Just a quick guess here, but {__?Positive, y__?test} must match the beginning of the list through to the end. So, {-1, 2, 3, 4, 5} fails on the first element, hence no print out. Try replacing Positive with ((Print[##];Positive[#])&), and you'll see it behaves in the same manner as the first pattern.
I think that your premise that Mathematica optimizes the pattern test is incorrect. Consider the pattern {x__, y__}. As you rightly say, there are 4 ways in which {1,2,3,4,5} can fit into this pattern. If you now add a pattern test to this with ?test, MatchQ should return True if any of the 4 ways match the pattern. So it must necessarily test all possible options until a match has been found. So the optimization is only when there are positives, and not when the pattern fails.
Here's a modification of your example with Positive, that shows you that Mathematica does not make the optimization as you claim:
test2 = (Print###; Positive###) &;
MatchQ[{-1, 2, 3, 4, 5}, {x__?test2, y__}]
It prints it 4 times! It terminates correctly with one print if the first element is indeed positive (thereby not having to test the rest). The test for the second element is applied only if the first is True, which is why the test for y was not applied in yours. Here's a different example:
test3 = (Print###; Negative###) &;
MatchQ[{1, 2, 3, 4, -5}, {x__?test2, y__?test3}]
I agree with your logic that if the first fails, then given that every element ought to match, all subsequent possibilities will also fail. My guess is that Mathematica is not that smart yet, and it is simpler to implement identical behaviour for any of _, __, or ___, rather than a different one for each. Implementing a different behaviour depending on whether you use __ or ___ will mask the true nature of the test and make debugging harder.
ok I'll have a go.
MatchQ[{1, 2, 3, 4, 5}, {x__?test, y__}]//Trace
shows that slot sequence is redundant because only one element, in this case the first one in the sequence, is tested. e.g.
MatchQ[{1, 2, 3, 4, 5}, {_, x__?test, y__}] // Trace
Now prints 3 twos. If you change the first pattern to BlankSequence more permutations are generated and some of these have different first elements
MatchQ[{1, 2, 3, 4, 5}, {__, x__?test, y__}] // Trace
In your final example
MatchQ[{-1, 2, 3, 4, 5}, {__?Positive, y__?test}]
the first element always fails the test. If you change this to
MatchQ[{1, 2, -3, 4, 5}, {__?Positive, y__?test}]
you will see something more along the lines of what you expected.
Definition "knows" the way how a value for a symbol was defined: using Set or SetDelayed. But how? As I understand, after a value for a symbol was assigned there is no any difference for the evaluator how it was assigned: by using Set or SetDelayed. It can be illustrated by the function OwnValues which always returns definitions with the Head RuleDelayed. How Definiton obtains this information?
In[1]:= a=5;b:=5;
Definition[a]
Definition[b]
OwnValues[a]
Out[2]= a=5
Out[3]= b:=5
Out[4]= {HoldPattern[a]:>5}
OwnValues[a] = {HoldPattern[a] -> 3}; OwnValues[a] gives {HoldPattern[a] :> 3} instead of {HoldPattern[a] -> 3} but Definition[a] shows what one can expect. Probably this definition is stored internally in the form of Rule but is converted to RuleDelayed by OwnValues for suppressing of evaluation of the r.h.s of the definition. This hypothesis contradicts my original understanding that there are no difference between values assigned by Set and SetDelayed. Probably such definitions are stored in different forms: Rule and RuleDelayed correspondingly but are equivalent from the evaluator's point of view.
It is interesting to see how MemoryInUse[] depends on the kind of definition.
In the following experiment I used the kernel of Mathematica 5.2 in interactive session without the FrontEnd. With the kernels of Mathematica 6 and 7 one will get different results. One reason for this is that in these versions Set is overloaded by default.
First of all I evaluate $HistoryLength=0; for having DownValues for In and Out variables not affecting my results. But it seems that even when $HistoryLength is set to 0 the value of In[$Line] for current input line is still stored and removed after entering new input. This is likely the reason why result of the first evaluation of MemoryInUse[] always differs from the second.
Here is what I have got:
Mathematica 5.2 for Students: Microsoft Windows Version
Copyright 1988-2005 Wolfram Research, Inc.
-- Terminal graphics initialized --
In[1]:= $HistoryLength=0;
In[2]:= MemoryInUse[]
Out[2]= 1986704
In[3]:= MemoryInUse[]
Out[3]= 1986760
In[4]:= MemoryInUse[]
Out[4]= 1986760
In[5]:= a=2;
In[6]:= MemoryInUse[]
Out[6]= 1986848
In[7]:= MemoryInUse[]
Out[7]= 1986824
In[8]:= MemoryInUse[]
Out[8]= 1986824
In[9]:= a:=2;
In[10]:= MemoryInUse[]
Out[10]= 1986976
In[11]:= MemoryInUse[]
Out[11]= 1986952
In[12]:= MemoryInUse[]
Out[12]= 1986952
In[13]:= a=2;
In[14]:= MemoryInUse[]
Out[14]= 1986848
In[15]:= MemoryInUse[]
Out[15]= 1986824
In[16]:= MemoryInUse[]
Out[16]= 1986824
One can see that defining a=2; increases MemoryInUse[] by 1986824-1986760=64 bytes. Replacing it with the definition a:=2; increases MemoryInUse[] by 1986952-1986824=128 bytes. And replacing the latter definition with the former reverts MemoryInUse[] to 1986824 bytes. It means that delayed definitions require 128 bytes more than immediate definitions.
Of course this experiment does not prove my hypothesis.
Complete definition for a symbol can be accessed via undocumented new-in-8 symbols Language`ExtendedDefinition and Language`ExtendedFullDefinition. Citing Oleksandr Rasputinov:
"If anyone is curious, Language`ExtendedDefinition and Language`ExtendedFullDefinition are analogous to Definition and FullDefinition but capture the definition of a symbol in such a way as it can be reproduced in another kernel. For example, defs = Language`ExtendedFullDefinition[sym] returns a Language`DefinitionList object. The syntax used to restore the definition is highly irregular: Language`ExtendedFullDefinition[] = defs, where defs is a Language`DefinitionList. Note that Language`ExtendedFullDefinition takes the ExcludedContexts option whereas Language`ExtendedDefinition does not."
Information calls Definition, and a Trace on Definition (or FullDefinition) shows nothing. I must assume that this is a low level function that accesses data outside of the *Values tables. Perhaps it keeps a copy of the original definition expressions as they were parsed at that time.
I would like to set up the following custom notation in Mathematica 7.
This notation is not particularly useful in itself, so please do not suggest existing alternatives, or point out that this only saves a few keystrokes.
I want to know if and how it may be done.
At present, one may enter
f = #2 + #^2 / #3 & ## # & ;
f[ {a, b, c} ]
Out[]= b + a^2 / c
Where the inner function #^2 / #3 + #2 & is Apply'd to the first argument.
I would like to implement the syntax
f = #2 + #^2 / #3 ##& ;
and have it behave exactly the same. That is, ##& to represent a Function that is automatically applied to its first argument.
It will need to have the same binding as the & symbol.
It is preferable that this is done with the Notations package, to whatever extent that is possible, rather than manual MakeBoxes, for the sake of ease in setting up similar notations, even though the use of Notations is more difficult to communicate via text.
You can't do this with an operator syntax of your own invention (like ##&). Mathematica just doesn't have the capability to modify the language grammar at runtime like that.
You can get at least partway there with the Notation package, but you have to use a symbol that has no meaning in Mathematica, and possibly most of the way there with one of the operators without built-in meanings, but most (if any) of them don't bind as postfix operators.
Here, for example, I'll use the Notations package to define the \[Wolf] character as an admittedly pseudo-postfix operator in place of ##&:
In[1]:= Needs["Notation`"]
In[2]:= Notation[x_ \[Wolf] \[DoubleLongLeftRightArrow] (x_ ## # &)]
In[3]:= f=#2+#^2/#3& \[Wolf]
Out[3]= (#2+#1^2/#3&) \[Wolf]
In[4]:= f[{a,b,c}]
Out[4]= b+a^2/c
I'll include a screenshot too since this involves notation:
Where this approach may fail is in the fact that you can't set an operator precedence for an arbitrary symbol like \[Wolf]. You can instead use one of the meaningless operators I linked to above, but those also have a fixed precedence that can't be changed.
If you found PrecedenceForm in the documentation you might get a brief false hope, but as the docs say, it only effects printing and not evaluation.
HTH!
I am wondering if given multiple substitution rules, how does mma determine which to apply first in case of collision. An example is:
x^3 + x^2*s + x^3*s^2 + s x /. {x -> 0, x^_?OddQ -> 2}
Thanks.
Mathematica has a mechanism which is able to determine the relative generality of the rules in simple cases, for example it understands that ___ (BlankNullSequence) is more general than __ (BlankSequence). So, when it can, it reorders global definitions according to it. It is important to realize though that such analysis is necessarily mostly syntactic. Therefore, while PatternTest (?) and Condition (/;) with some simple built-in predicates like EvenQ can sometimes be analyzed, using them with user-defined predicates will necessarily make such reordering impossible with respect to similarly defined rules, so that Mathematica will keep such rules in the order they were entered. This is because, PatternTest and Condition force the pattern-matcher to call evaluator to determine the fact of the match, and this makes it impossible to answer the question of relative generality of rules at definition - time. Even for purely syntactic rules it is not always possible to determine their relative generality. So, when this can not be done, or Mathematica can not do it, it keeps the rules in the order they were entered.
This all was about global rules, created by Set or SetDelayed or other assignment operators. For local rules, like in your example, there is no reordering whatsoever, they are applied in the order they have in the list of rules. All the rules in the list of rules beyond the first one that applied to a given (sub)expression, are ignored for that subexpression and that particular rule-application process - the (sub)expression gets rewritten according to the first matching rule, and then the rule-application process continues with other sub-expressions. Even if the new form of the rewritten (sub) expression matches some rules further down the rule list, they are not applied in this rule-application process. In other words, for a single rule-application process, for any particular (sub) expression, either no rule or just one rule is applied. But here also there are a few subtleties. For example, ReplaceAll (/.) applies rules from larger expressions to sub-expressions, while Replace with explicit level specification does it in the opposite way. This may matter in cases like this:
In[1]:= h[f[x, y]] /. {h[x_f] :> a, f[args__] :> b}
Out[0]= a
In[2]:= Replace[h[f[x, y]], {h[x_f] :> a, f[args__] :> b}, {0, Infinity}]
Out[2]= h[b]
I mentioned rule reordering in a few places in my book:here, here, and here. In rare cases when Mathematica does reorder rules in a way that is not satisfactory, you can change the order manually by direct manipulations with DownValues (or other ...Values), for example like DownValues[f] = Reverse[DownValues[f]]. Such cases do occur sometimes, but rather rarely, and if they happen, make sure there is a good reason to keep the existing design and go for manual rule reordering.
The mathematica documentation on Evaluate at possible issues says:
Evaluate works only on the first
level, directly inside a held function
Why does Mathematica have this limitation? So if I have an expression with more than one level take this simplified example:
Hold[Plus[Plus[2, 2], 2]]]
Now suppose I want to see what the answer is to the the second Plus, without evaluating anything on levels below it. I've tried different things such as:
In[290]:= Hold[Plus[Evaluate[Plus[2, 2]], 2]]
Out[290]= Hold[Evaluate[2+2]+2]
In[287]:= Hold[Plus[ReleaseHold[Hold[Plus[2, 2]]], 2]]
Out[287]= Hold[ReleaseHold[Hold[2+2]]+2]
The first Hold keeps everything unevaluated at and beyond the first level in this case.
The goal is to control evaluation of an expression at each stage from the most inner nested function to the outer one using successive Hold, ReleaseHold and Evaluate functions to achieve that. I know I could use trace to see what happens beyond level one in an expression but that is different and sometimes complex to read with longer expressions.
It seems like the only way is to extract and totally dismantle the expression into lists using Extract, Part or Level; evaluate part of the expression that I want; then reconstruct and re-map the expression back together for each stage. Are there any other approaches or functions for achieving this I could consider?
Edit: This might be a better example to look at the approach of releasing the first hold. With the expression:
Hold[Plus[Plus[2, Plus[2,2]], 2]]]
If you release the first hold and place a hold on a higher level in a expression at the third Plus, to look like this:
in = Plus[Plus[2, Hold[Plus[2,2]]], 2]]]
out = Hold[2+2]+4
You find that Mathematica will evaluate lower levels in the background when you really want it to wait.
I can't give the exact reason why Evaluate "works only on the first level, directly inside a held function" but I suspect it's partly efficiency, in that it would be slow if the evaluator had to scan the complete expression tree of held arguments passed to any function with a Hold* attribute for nested Evaluate expressions and evaluate them, and then recurse and look for Evaluate subexpressions in what it just evaluated, all while keeping the rest of the expression unevaluated, especially when this might not always be what you want to happen anyway.
Doing what you want is pretty easy using a combination of Extract and ReplacePart though:
In[51]:= expr = Hold[Plus[Plus[2, 2], 2]];
In[52]:= ReleaseHoldAt[expr_, partspec_] :=
ReplacePart[expr, partspec -> Extract[expr, partspec]]
In[53]:= ReleaseHoldAt[expr, {1, 1}]
Out[53]= Hold[4 + 2]
This lets us illustrate another reason why it might not make sense for Evaluate to work at any level in an expression passed as an argument to a function with a Hold* attribute, considering the following expression involving i:
In[82]:= i = 1;
In[83]:= ReleaseHoldAt[Hold[i = 2; j = Plus[i, i]], {1, 2}]
Out[83]= Hold[i = 2; 2]
Note that the value of j would have been 4 if we had evaluated the first part of that expression before the Plus, but the results are different since we are only doing partial evaluation, and i=2 had not been evaluated when we evaluated the subexpression setting j. Sometimes, this may be what you want to happen, but often it is very likely not.
Keep in mind that even Evaluate in the first level can be defeated by a function that has the attribute HoldAllComplete or by using HoldComplete:
In[62]:= Hold[Evaluate[Plus[2,2]]]
Out[62]= Hold[4]
...versus:
In[63]:= HoldComplete[Evaluate[Plus[2,2]]]
Out[63]= HoldComplete[Evaluate[2+2]]
Finally, the output of Trace can be a little dense, but you can filter out what you want by using patterns or symbols of interest in the second argument:
In[88]:= Trace[Plus[Plus[Plus[1,2],3],4],Plus]
Out[88]= {{{1+2,3},3+3,6},6+4,10}
In[93]:= Trace[Plus[Subtract[Plus[1,2],4],8],_Plus]
Out[93]= {{{1+2}},-1+8}
HTH!
As is so often the case when you want to do something tricky in Mathematica, pattern matching and rule replacement come to the rescue. However, in this instance, you have to do something weird, and you have to use Replace instead of ReplaceAll (the /. operator) so you can take advantage of its optional third argument to give it a level specification. Using the example you offered:
In[1]:= Replace[
Hold[Plus[Plus[2, 2], 2]],
expr_Plus :> With[{eval = expr}, eval /; True],
{2}]
Out[1]= Hold[4 + 2]
The useless-looking
expr_Plus :> With[{eval = expr}, eval /; True]
rule is actually a documented way to share local variables between the test match and the body of the With structre; here you don't do anything with the local variable but force its evaluation in a roundabout way---because less roundabout ways won't work!
EDIT to add: I think you're mis-interpreting the result of Level; the two expressions at level {2} of this expression are 2 and Plus[2, 2]; you can see this by using the optional third argument to level, which does something similar to the optional third argument of Extract:
In[2]:= Level[Hold[Plus[Plus[2, 2], 2]], {2}, Hold]
Out[2]= Hold[2 + 2, 2]
With the {2} level spec, Replace will try to match-and-replace the rule against these two expressions, and it will work on the second one.
A technique which does not involve Extractis to wrap the parts inside Hold in inner Holds, and then release the outer Hold:
expr=Hold[(1+2)+3];
ReleaseHold#Map[Hold,expr,{2}]
Out[2]= Hold[3]+Hold[1+2]
You can play various games in this direction, but since I can't tell what it is you want to do, it is a bit hard to be specific. Something that might be useful is to define your own Hold that descents however you want it to:
SetAttributes[DescentHold,{HoldAll}]
DescentHold[a_Plus]:=ReleaseHold#Map[DescentHold,Hold[a],{2}]
DescentHold[a_]:=Hold[a]
Note that this one approaches the outer Holds once the insides are wrapped, so that for instance the flatness of Plus kicks in:
DescentHold[2*3+(4+5)]
Out[4]= Hold[4]+Hold[5]+Hold[2*3]
Using the idea about ReplacePart and Extract functions from the answer by Michael Pilat, one can write HoldAndEvaluate function, which allows him to evaluate a desired part of the expression without the need to calculate its position (it can be marked with "MyEvaluate").
In[1]:= expr = Hold[MyEvaluate[2 + 2] + 2];
In[2]:= HoldAndEvaluate[expr_] :=
ReplacePart[expr,
# -> Evaluate ## Extract[expr, #] & /#
Position[expr, MyEvaluate[_]] ];
In[3]:= HoldAndEvaluate[expr]
Out[3]= Hold[4 + 2]