MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: := vs = in some function definitions

On 10/20/10 at 4:06 AM, sam.takoy at (Sam Takoy) wrote:

>Have read everything I could find regarding delayed assignment, I'm
>still not quite sure when to use which.

>For example, in the definition

>f[x_] = IdentityMatrix[50].Append[Range[1, 49], x];

>could there ever be any reason to use :=   ?

Consider the following:

In[1]:= x = 4;
f[x_] = x^2

Out[2]= 16

In[3]:= f[5]

Out[3]= 16

The result obtained for f[5] is probably not what you would want.

>It seems that using   :=  will condemn the function to repeated
>extra work every time its called.


>So could there be a situation where the use of ":=" for the above
>function is recommended?

Consider a different problem where x is not assigned a value
before the function is assigned.

In[1]:= f[x_] = RandomInteger[{1, 10}] x

Out[1]= 9 x

In[2]:= f[3]

Out[2]= 27

In[3]:= f[2]

Out[3]= 18

Here, the evaluation of RandomInteger only once means the
function result will no longer be a random multiple of x. This
would obviously be a problem for a simulation of a random process.

  • Prev by Date: Re: Tree with repeated labels
  • Next by Date: Re: := vs = in some function definitions
  • Previous by thread: Re: := vs = in some function definitions
  • Next by thread: Re: := vs = in some function definitions