summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorJosep Sanjuas <jsanjuas@gmail.com>2015-04-12 19:40:30 +0200
committerJosep Sanjuas <jsanjuas@gmail.com>2015-04-12 19:40:30 +0200
commitd0ff06b8c14e3b505d0c14ca5c9c37e8b667c875 (patch)
tree42b258749d641870306699ab1388b54408d189a8
parent28ecf72f79efa55f48b4ecd7cbe4ca29ccaa0f95 (diff)
downloadNim-d0ff06b8c14e3b505d0c14ca5c9c37e8b667c875.tar.gz
Generalize mean to other types
-rw-r--r--lib/pure/math.nim7
1 files changed, 5 insertions, 2 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim
index aa64933fb..0051c9d88 100644
--- a/lib/pure/math.nim
+++ b/lib/pure/math.nim
@@ -114,10 +114,13 @@ 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.} = 
+template toFloat(f: float): float = f
+
+proc mean*[T](x: openArray[T]): float {.noSideEffect.} =
   ## computes the mean of the elements in `x`. 
   ## If `x` is empty, NaN is returned.
-  result = sum(x) / toFloat(len(x))
+  ## ``toFloat(x: T): float`` must be defined.
+  result = toFloat(sum(x)) / toFloat(len(x))
 
 proc variance*(x: openArray[float]): float {.noSideEffect.} = 
   ## computes the variance of the elements in `x`.