[?] Why is Evaluate Required Here?

Although I have used Mathematica for a while I still consider myself a noobie. I still don’t understand the fundamental concepts of many of the functions. My question in this case is why I need the Evaluate function to make the following example code work?

eqn = y'[t] == 2;
yList = {.2, .4, .5};
eventList = Map[y[t] == # &, yList];
{fun, dat} = 
 Reap@NDSolve[{eqn, y[0] == 0, 
    WhenEvent[Evaluate[eventList], {tdat = t; Sow[tdat]}]}, 
   y[t], {t, 0, 5}]

Without the Evaluate operating on eventList the NDSolve returns an empty list.

Mike,

WhenEvent has the attribute HoldAll.

In[11]:= Attributes[WhenEvent]

Out[11]= {HoldAll, Protected}

This means that it will not evaluate eventlist and “eventlist” unevaluated does not have any conditions that trigger an event. You can only trigger an event if you evaluate eventlist to obtain the equality conditions.

You should look at Non-standard Evaluation to explain this further.

Regards

Neil

Thanks Neil.

This means that it will not evaluate eventlist

What HoldAll actually means is that the arguments will not be evaluated before being passed to WhenEvent. The function itself is free to do anything it wants with them, including evaluation.

Evaluate is needed here since you are building the list of events programmatically. Without it, when passed in, it’s just an expression with head Map (not an explicit List which tells WhenEvent to set up multiple events) and given numeric values it would never evaluate to False or True, so no events will be detected.

Thanks Ilian. Your explanation gives me a better understanding of the processing going on behind the front end.