Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: := vs = in some function definitions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113273] Re: := vs = in some function definitions
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Thu, 21 Oct 2010 07:03:45 -0400 (EDT)

On 10/20/10 at 4:06 AM, sam.takoy at yahoo.com (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.

Exactly.

>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