错误,(在addList中)无效的下标选择器

时间:2013-06-03 00:11:29

标签: maple

我有一个数字列表,我想添加它们,然后将它们乘以常数。

addList := proc(a::list,b::integer)::integer;
local x,i,s;
description "add a list of numbers and multiply by a constant";
x:=b;
s:=0;
for i in a do
    s:=s+a[i];
end do;
s:=s*x;
end proc;

sumList:= addList([2,2,3],2)工作正常,但同时sumList:= addList([20,20,30],2)给出错误。 有人可以指出错误吗?

2 个答案:

答案 0 :(得分:2)

在for循环中,您执行s:=s+a[i]但我将其设置为已经存在的值之一 - 而不是值的索引。第一步修复只是将上面的语句更改为s:=s+i

你也可以把这个函数写成

proc(a::list,b::integer)::integer; 
   convert(a,`+`)*b; 
end;

答案 1 :(得分:1)

更短,有

addList:= (a,b)-> `+`(a[])*b;