Speed improvement for sum() in vector and list of vectors case

This commit is contained in:
Adrian Mariano 2020-06-13 20:39:45 -04:00
parent 39de8491a3
commit 224555a9ec

View file

@ -438,8 +438,11 @@ function lcm(a,b=[]) =
// sum([1,2,3]); // returns 6.
// sum([[1,2,3], [3,4,5], [5,6,7]]); // returns [9, 12, 15]
function sum(v, dflt=0) =
is_vector(v) ? [for(i=v) 1]*v :
assert(is_consistent(v), "Input to sum is non-numeric or inconsistent")
len(v) == 0 ? dflt : _sum(v,v[0]*0);
is_vector(v[0]) ? [for(i=v) 1]*v :
len(v) == 0 ? dflt :
_sum(v,v[0]*0);
function _sum(v,_total,_i=0) = _i>=len(v) ? _total : _sum(v,_total+v[_i], _i+1);