Maxima block and variable

自闭症网瘾萝莉.ら 提交于 2019-12-12 03:45:38

问题


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]


来源:https://stackoverflow.com/questions/42819545/maxima-block-and-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!