Maxima block and variable

2019-09-15 02:30发布

问题:

I want to display the square of numbers 1 to 5 using block command:

expr : 10*i;

myList (expr, iMin, iMax) := block(
  local(expr),
  print(expr),
  print(''expr),
  print( makelist(expr, i, iMin, iMax)),
  print( makelist(''expr, i, iMin, iMax)) 
 )$

ai : i^2$
myList (ai,1,5);

Here's what I get with this code:

i^2
10*i
[i^2,i^2,i^2,i^2,i^2]
[10,20,30,40,50]

Why the "expr" variable (with quote quote) in the myList is not the variable "ai"?

回答1:

The short answer is that quote-quote is applied only at the time the expression is input, not when it is evaluated. Try grind(myList); to see that quote-quote has interpolated (pasted) the current value of expr into the function definition.

The longer answer is that Maxima generally has a one-time evaluation policy (i.e. variables are evaluated just once), but some functions "quote" (do not evaluate) their arguments or evaluate their arguments in a peculiar way, and makelist is one of those. That makes it tricky to write a function like myList which wants to supply an argument to makelist.

My advice is to write apply(makelist, [...]) (i.e. apply makelist to the list of arguments) instead of makelist(...). Writing it with apply will ensure that the arguments are evaluated.

(%i5) myList(expr, iMin, iMax) := apply (makelist, [expr, i, iMin, iMax]) $
(%i6) expr:i^2 $
(%i7) myList(expr, 1, 5);
(%o7)                          [1, 4, 9, 16, 25]


标签: maxima