Example:
list:={ Plus[1,1], Times[2,3] }
When looking at list, I get
{2,6}
I want to keep them unevaluated (as above) so that list returns
{ Plus[1,1], Times[2,3] }
Later I want to evaluate the functions in list sequence to get
{2,6}
The number of unevaluated functions in list is not known beforehand. Besides Plus, user defined functions like f[x_] may be stored in list
I hope the example is clear.
What is the best way to do this?
The best way is to store them in
Hold, notList, like so:In this way, you have full control over them. At some point, you may call
ReleaseHoldto evaluate them:If you want the results in a list rather than
Sequence, you may use justList@@lhinstead. If you need to evaluate a specific one, simply usePartto extract it:If you insist on your construction, here is a way:
EDIT
In case you have some functions/symbols with
UpValueswhich can evaluate even insideHold, you may want to useHoldCompletein place ofHold.EDIT2
As pointed by @Mr.Wizard in another answer, sometimes you may find it more convenient to have
Holdwrapped around individual items in your sequence. My comment here is that the usefulness of both forms is amplified once we realize that it is very easy to transform one into another and back. The following function will split the sequence insideHoldinto a list of held items:for example,
grouping them back into a single
Holdis even easier – justApplyJoin:The two different forms are useful in diferrent circumstances. You can easily use things such as
Union,Select,Caseson a list of held items without thinking much about evaluation. Once finished, you can combine them back into a singleHold, for example, to feed as unevaluated sequence of arguments to some function.EDIT 3
Per request of @ndroock1, here is a specific example. The setup:
placing functions in
Hold:Here is how the
execfunction may look:Now,
Note that the original variable
heldremains unchanged, since we operate on the copy. Note also that the original setup contains mutable state (l), which is not very idiomatic in Mathematica. In particular, the order of evaluations matter:Whether or not this is desired depends on the specific needs, I just wanted to point this out. Also, while the
execabove is implemented according to the requested spec, it implicitly depends on a global variablel, which I consider a bad practice.An alternative way to store functions suggested by @Mr.Wizard can be achieved e.g. like
In[63]:= listOfHeld = splitHeldSequence[held]
Out[63]= {Hold[Z1], Hold[S1]}
and here
The same comments about mutability and dependence on a global variable go here as well. This last form is also more suited to query the function type:
for example: