From 019961aef79776831e1672225a280cf91e5f9b04 Mon Sep 17 00:00:00 2001
From: Revar Desmera <revarbat@gmail.com>
Date: Sat, 8 Feb 2020 21:54:39 -0800
Subject: [PATCH] Added dflt= arg to sum(), defaulting to 0.

---
 math.scad            | 8 +++++---
 tests/test_math.scad | 3 +++
 version.scad         | 2 +-
 3 files changed, 9 insertions(+), 4 deletions(-)

diff --git a/math.scad b/math.scad
index f6b4c2d..aa6a096 100644
--- a/math.scad
+++ b/math.scad
@@ -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()
diff --git a/tests/test_math.scad b/tests/test_math.scad
index 5a93cfc..2103ed0 100644
--- a/tests/test_math.scad
+++ b/tests/test_math.scad
@@ -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]);
diff --git a/version.scad b/version.scad
index ffa5a4f..ff55c15 100644
--- a/version.scad
+++ b/version.scad
@@ -8,7 +8,7 @@
 //////////////////////////////////////////////////////////////////////
 
 
-BOSL_VERSION = [2,0,118];
+BOSL_VERSION = [2,0,119];
 
 
 // Section: BOSL Library Version Functions