Application Center - Maplesoft

App Preview:

Maple Programming: 2.3: Levels of evaluation

You can switch back to the summary page by clicking here.

Learn about Maple
Download Application


 

2.03.mws

Programming in Maple

Roger Kraft
Department of Mathematics, Computer Science, and Statistics
Purdue University Calumet

roger@calumet.purdue.edu

2.3 Levels of evaluation

Let us go back to the first example of full evaluation defined earlier.

>    x:='x': y:='y': z:='z':

>    x:=y;

>    y:=z;

>    z:=3;

x := y

y := z

z := 3

Now if we ask Maple to evaluate x , Maple uses full evaluation and returns 3.

>    x;

3

But for Maple to get from x  to 3 it had to go through the intermediate values of y  and z . There is a name for these intermediate values and there is a way to access them also. The name for these intermediate values is levels of evaluation  and we can control the level of evaluation using a special form of the eval  command. For example, here is how we get one level of evaluation of x , which returns the name y .

>    eval( x, 1 );

y

Here is how we get two levels of evaluation of x , which returns the name z .

>    eval( x, 2 );

z

Here is how we get three levels of evaluation of x , which returns the value 3.

>    eval( x, 3 );

3

We can ask for four or higher levels of evaluation, but 3 always evaluates to 3.

>    eval( x, 4 );

3

>   

Let us unassign the variables that we have used so far.

>    unassign('x','y','z');

Here is another example using levels of evaluation.

>    f := a*x+b*y;

>    x := y;

>    y := z;

>    z := 2;

>    b := c;

>    c := a;

>    a := d;

f := a*x+b*y

x := y

y := z

z := 2

b := c

c := a

a := d

Now evaluate f  to several different levels. Mentally check each level of evaluation yourself to make sure that you understand what the eval  command is doing.

>    eval( f, 1 );

a*x+b*y

>    eval( f, 2 );

d*y+c*z

>    eval( f, 3 );

d*z+2*a

>    eval( f, 4 );

4*d

>   

Exercise : Redo the last example. Can you explain why the results of the example are different the second time that you go through it? How can you get the example to work again like it did the first time?

>   

Levels of evaluation do not work when functions are involved. Consider this example.

>    g := u*sin(u+v);

>    u := s;

>    v := t;

>    s := t;

>    t := Pi/4;

g := u*sin(u+v)

u := s

v := t

s := t

t := 1/4*Pi

Now try using levels of evaluation.

>    eval( g, 1 );

u*sin(u+v)

>    eval( g, 2 );

s*sin(u+v)

>    eval( g, 3 );

t*sin(u+v)

>    eval( g, 4 );

1/4*Pi*sin(u+v)

>    eval( g, 5 );

1/4*Pi*sin(u+v)

Notice that nothing is being evaluated inside the sin  function. However, if we use the eval  command without any level parameter, then everything is fully evaluated.

>    eval( g );

1/4*Pi

>   

>   

>