Added dflt= arg to sum(), defaulting to 0.

This commit is contained in:
Revar Desmera 2020-02-08 21:54:39 -08:00
parent a78973187a
commit 019961aef7
3 changed files with 9 additions and 4 deletions

View File

@ -428,14 +428,16 @@ function lcm(a,b=[]) =
// Description:
// Returns the sum of all entries in the given list.
// If passed an array of vectors, returns a vector of sums of each part.
// If passed an empty list, the value of `dflt` will be returned.
// Arguments:
// v = The list to get the sum of.
// dflt = The default value to return if `v` is an empty list. Default: 0
// Example:
// sum([1,2,3]); // returns 6.
// sum([[1,2,3], [3,4,5], [5,6,7]]); // returns [9, 12, 15]
function sum(v, _i=0, _acc) =
_i>=len(v)? _acc :
sum(v, _i=_i+1, _acc=is_undef(_acc)? v[_i] : _acc+v[_i]);
function sum(v, dflt=0, _i=0, _acc) =
_i>=len(v)? (len(v)? _acc : dflt) :
sum(v, dflt=dflt, _i=_i+1, _acc=is_undef(_acc)? v[_i] : _acc+v[_i]);
// Function: cumsum()

View File

@ -293,6 +293,8 @@ test_atanh();
module test_sum() {
assert(sum([]) == 0);
assert(sum([],dflt=undef) == undef);
assert(sum([1,2,3]) == 6);
assert(sum([-2,-1,0,1,2]) == 0);
assert(sum([[1,2,3], [3,4,5], [5,6,7]]) == [9,12,15]);
@ -301,6 +303,7 @@ test_sum();
module test_cumsum() {
assert(cumsum([]) == []);
assert(cumsum([1,1,1]) == [1,2,3]);
assert(cumsum([2,2,2]) == [2,4,6]);
assert(cumsum([1,2,3]) == [1,3,6]);

View File

@ -8,7 +8,7 @@
//////////////////////////////////////////////////////////////////////
BOSL_VERSION = [2,0,118];
BOSL_VERSION = [2,0,119];
// Section: BOSL Library Version Functions