Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss
Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Re: using predefined expressions in functions [newbie

1 view
Skip to first unread message

Leonid Shifrin

unread,
May 28, 2009, 4:27:56 AM5/28/09
to
Hi,

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
functions
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

Regards,
Leonid


On Wed, May 27, 2009 at 1:05 AM, ChangMo <nichthi...@gmail.com> 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
>
>

Bob Hanlon

unread,
May 28, 2009, 4:28:27 AM5/28/09
to
R1 := {x1, y1, z1}
R2 := {x2, y2, z2}

Don' t use SetDelayed in definition of f

f[x1_, y1_, z1_, x2_, y2_, z2_] = R1.R2;

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

32


Bob Hanlon

---- ChangMo <nichthi...@gmail.com> wrote:

=============

0 new messages