Pregunta

I have a list of numbers and I want to add them and then multiply them by a constant.

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) works fine but at the same time sumList := addList([20, 20, 30], 2) gives an error. Can somebody point out the error ?

¿Fue útil?

Solución

In the for loop you do s:=s+a[i] but i is set to one of the values in a already - not the index of a value. A first pass fix would be to just change the statement above to s:=s+i.

You could also write the function as

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

Otros consejos

Even shorter, there is

addList:= (a,b)-> `+`(a[])*b;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top