Explore the latest version of An Elementary Introduction to the Wolfram Language »
39Immediate and Delayed Values
In immediate assignment, the value is computed immediately when the assignment is done, and is never recomputed. In delayed assignment, the computation of the value is delayed, and is done every time the value is requested.
In immediate assignment (=), a random color is immediately generated:
In[1]:=
Click for copyable input
Out[1]=
Every time you ask for value, you get the same random color:
In[2]:=
Click for copyable input
Out[2]=
In delayed assignment (:=), no random color is immediately generated:
In[3]:=
Click for copyable input
Each time you ask for value, RandomColor[] is computed, and a new color is generated:
In[4]:=
Click for copyable input
Out[4]=
The color will typically be different every time:
In[5]:=
Click for copyable input
Out[5]=
Its very common to use := if something isnt ready yet when youre defining a value.
You can make a delayed assignment for circles even though n doesnt yet have a value:
In[6]:=
Click for copyable input
Give n a value:
In[7]:=
Click for copyable input
Out[7]=
In[8]:=
Click for copyable input
Out[8]=
The idea of delayed assignment is directly analogous to the Delayed construct we discussed for deploying webpages. In delayed assignment we dont compute a value until we need it. Similarly, when we use CloudDeploy with Delayed we dont compute the content of a webpage until someone asks for it.
Theres a notion of delayed rules too. xrhs computes rhs immediately. But in a delayed rule xrhs (typed :>), rhs is instead recomputed every time its requested.
This is an immediate rule, where a specific value for RandomReal[ ] is immediately computed:
In[9]:=
Click for copyable input
Out[9]=
You can replace four xs, but theyll all be the same:
In[10]:=
Click for copyable input
Out[10]=
This is a delayed rule, where the computation of RandomReal[] is delayed:
In[11]:=
Click for copyable input
Out[11]=
RandomReal[] is computed separately when each x is replaced, giving four different values:
In[12]:=
Click for copyable input
Out[12]=
39.1Replace x in {x, x+1, x+2, x^2} by the same random integer up to 100. »
Sample expected output:
Out[]=
39.2Replace each x in {x, x+1, x+2, x^2} by a separately chosen random integer up to 100. »
Sample expected output:
Out[]=
Because you dont want to have to recompute things unless its necessary. Its more efficient to just compute something once, then use the result over and over again.
How does one read := and :> out loud?
:= is usually just colon equals, though sometimes delayed assignment. :> is usually colon greater, though sometimes delayed rule.
Youll start an infinite loop thatll eventually get cut off by the system. x={x} is the same story.
It indicates that inputs are assigned to In[n] and outputs to Out[n]. The := for input means the assignment is delayed, so that if you ask for In[n] the result will be recomputed.
 
Download Notebook Version
es