Call by reference in maxima: is it possible?

Viewed 54

I'm trying to simplify the notation of a recurring operation I use inside my function block definitions in Maxima. For instance, instead of writing

a: endcons(a,b),

everytime, I want to replace this for

a<-b.

However, if I define

infix("<-")$
"<-"(a,b):= a: endcons(a,b)

I'll obviously never get the list a to receive a new entry b at its end:

(%i1)   infix("<-");
(%o1)               "<-"
(%i50)  "<-"(a,b):= a: endcons(b,a);
(%o50)              a \<\- b:=a:endcons(b,a)
(%i48)  a:[];
(a)                 []
(%i51)  a<-b;
(%o51)              [b]
(%i52)  a;
(%o52)              []

because a and b are called by value in the function/operator call. Is there any way I can get "<-" to call a by reference, so I can change the value of a in the global context, even when a is called as an argument?

1 Answers

Hmm, this inspires various thoughts. (1) You can get the effect you want with the built-in function push, e.g.: push(b, a) appends b to the list bound to a.

(2) Aside from the built-in function, the kind of operation you want is probably most easily implemented in Maxima as a so-called macro, which is just a function which returns an expression which is then evaluated. E.g.: "<-"(a, b) ::= buildq([a, b], a: endcons(b, a)). Note that macroexpand(a <- b) yields a:endcons(b,a) and macroexpand(p <- q) yields p:endcons(q,p). Then if you just write a <- b or p <- q you'll get the result you were thinking of. Note that buildq is really just a substitution function which quotes the expression into which one is substituting values.

(3) My advice about working with collections such as lists is to think about how you can get the desired result all in one go, instead of incrementally building it. For example, maybe you can use sublist or map or makelist to construct the result. This is part of a bigger topic, namely functional programming, which is just programming without side effects -- the absence of side effects makes the program easier to comprehend, which is the most important optimization.

Related