MathGroup Archive 2009

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

Search the Archive

Re: using predefined expressions in functions [newbie


This is a problem of scope.  You use SetDelayed (:=) (which is generally a
right thing when defining a function), which does not evaluate the r.h.s.
The resulting definition of <f> does not know about you parameters:

In[1] = DownValues[f]

Out[1] = {HoldPattern[f[x1_, y1_, z1_, x2_, y2_, z2_]] :> R1.R2}

The parameter - passing is a 2-step process: first, the porameters
are substituted textually into the code of the r.h.s as present in ...Values
(DownValues in this case), then the resulting code is evaluated. In your
case, no substitution takes place in step 1 since R1 and R2 are just symbols
- they do not explicitly (literally) contain x1, y1, etc. Since the step 1
was idle, the step 2 just uses symbolic expression for R1, R2 that you
defined - hence your answer.

The simplest solution in your case is to use Set, making sure that your
variables don't have global values (use Clear for instance):

In[2] =

Clear[x1, x2, y1, y2, z1, z2];
f[x1_, y1_, z1_, x2_, y2_, z2_] = R1.R2;

In[3] =

f[1, 2, 3, 4, 5, 6]

Out[3] = 32

Note that in general using proxies like R1, R2 and then Set to define
is  error - prone. It is better to either use the actual expressions on the
r.h.s or make R1, R2 functions and either way  use SetDelayed:

In[4] =

Clear[R1, R2, f];
R1[x_, y_, z_] := {x, y, z};
R2[x_, y_, z_] := {x, y, z};
f[x1_, y1_, z1_, x2_, y2_, z2_] := R1[x1, y1, z1].R2[x2, y2, z2]

In[5] = f[1, 2, 3, 4, 5, 6]

Out[5] = 32


On Wed, May 27, 2009 at 1:05 AM, ChangMo <nichthierwohne at> wrote:

> Hi,
> I've been trying to write a function using some predefined
> expressions, but the function assignment seems to understand the
> symbols in the expressions as literals. eg.,
> Needs["VectorAnalysis`"]
> R1 := {x1,y1,z1}
> R2 := {x2,y2,z2}
> f[x1_,y1_,z1_,x2_,y2_,z2_] := R1 . R2
> f[1,2,3,4,5,6]
> gives the output
> x1 x2 + y1 y2 + z1 z2
> instead of
> 32 ( = 1*4 + 2*5 + 3*6 )
> Can anyone help me with this?  Thanks for your attention.
> -ChangMo

  • Prev by Date: Re: simultaneous equations for chemical speciation
  • Next by Date: Re: Dynamic performance - input fields slow
  • Previous by thread: using predefined expressions in functions [newbie question]
  • Next by thread: Re: using predefined expressions in functions [newbie question]