summary refs log tree commit diff stats
path: root/lib/pure
diff options
context:
space:
mode:
authorVarriount <Varriount@users.noreply.github.com>2015-05-07 12:59:01 -0400
committerVarriount <Varriount@users.noreply.github.com>2015-05-07 12:59:01 -0400
commitace11f08aa8af28a3a9faa44a0f9604a703b1e4a (patch)
tree77f96f4447bd3248e0cc3639cf701ebc9184831c /lib/pure
parentd8827188826ebecda132160c2992959cb045d37e (diff)
parentf72bb57fff29609336beae56ae148e20d0dd702e (diff)
downloadNim-ace11f08aa8af28a3a9faa44a0f9604a703b1e4a.tar.gz
Merge pull request #2537 from jsanjuas/devel
Generalize mean to other types
Diffstat (limited to 'lib/pure')
-rw-r--r--lib/pure/math.nim17
1 files changed, 11 insertions, 6 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim
index a5013a3ad..cb58ea39b 100644
--- a/lib/pure/math.nim
+++ b/lib/pure/math.nim
@@ -114,18 +114,23 @@ proc sum*[T](x: openArray[T]): T {.noSideEffect.} =
   ## If `x` is empty, 0 is returned.
   for i in items(x): result = result + i
 
-proc mean*(x: openArray[float]): float {.noSideEffect.} = 
-  ## computes the mean of the elements in `x`. 
+template toFloat(f: float): float = f
+
+proc mean*[T](x: openArray[T]): float {.noSideEffect.} =
+  ## computes the mean of the elements in `x`, which are first converted to floats.
   ## If `x` is empty, NaN is returned.
-  result = sum(x) / toFloat(len(x))
+  ## ``toFloat(x: T): float`` must be defined.
+  for i in items(x): result = result + toFloat(i)
+  result = result / toFloat(len(x))
 
-proc variance*(x: openArray[float]): float {.noSideEffect.} = 
+proc variance*[T](x: openArray[T]): float {.noSideEffect.} =
   ## computes the variance of the elements in `x`. 
   ## If `x` is empty, NaN is returned.
+  ## ``toFloat(x: T): float`` must be defined.
   result = 0.0
   var m = mean(x)
-  for i in 0 .. high(x):
-    var diff = x[i] - m
+  for i in items(x):
+    var diff = toFloat(i) - m
     result = result + diff*diff
   result = result / toFloat(len(x))