block, for and variable scope



On 5/12/07, Robert Willam Grieve <sonofthejedi at xtra.co.nz> wrote:
>
> Ok, umm, I got it to work, but I have no idea why, as I didn't
> change move. Can someone please explain why this now produces
> the expected result.


I don't know why you're now getting the expected result, but here are some
hints on using the Maxima language:

> (%t6) move(curpos,dir) := block
> (
>    [curpos:curpos,dir:dir],


Function parameters are already local to the function, so you don't need to
rebind them this way. In fact, you don't need a block at all.

   if equal(dir,0) then


I assume that dir is always a number 0-3, in which case you can use "="
here.

      return(curpos[first(curpos)+1,second(curpos)]) ,


You can use an if/then/else instead of a series of if/then, making it one
expression.

Then you don't need "return" -- the value of the last expression in a block
is returned as the block's value.

You can add vectors componentwise (if listarith is true, the default) with
"+" e.g. curpos+[1,0].

You don't need to assign to curpos.

Since all clauses are curpos+xxx, you can move the conditional inside, that
is

      curpos + ( if dir=0 then [1,0] ...)

And why not keep the direction vectors in an array or list?

   if equal(dir,1) then
>       return(curpos:[first(curpos),second(curpos)+1]) ,
>    if equal(dir,2) then
>       return(curpos:[first(curpos)-1,second(curpos)]) ,
>    if equal(dir,3) then
>       return(curpos:[first(curpos),second(curpos)-1])


It is good practice to have an "else" to catch errors.

)


I won't write out the result of applying these hints, in case this is a
homework assignment....  But I will tell you that the result is one short
line long.

             -s