]> gitweb.factorcode.org Git - factor.git/commitdiff
better minmax
authorDoug Coleman <doug.coleman@gmail.com>
Mon, 7 Dec 2009 23:26:33 +0000 (17:26 -0600)
committerDoug Coleman <doug.coleman@gmail.com>
Mon, 7 Dec 2009 23:26:33 +0000 (17:26 -0600)
basis/math/statistics/statistics-docs.factor
basis/math/statistics/statistics.factor

index 9834f44add4167491d2d154b7b26e4bcf81b5d4b..bbfc787c0ffa4078335fd5f4a725b843abb54301 100644 (file)
@@ -38,7 +38,7 @@ HELP: range
 
 HELP: minmax
 { $values { "seq" sequence } { "min" real } { "max" real } }
-{ $description "Finds the minimum and maximum elements of " { $snippet "seq" } " in one pass." }
+{ $description "Finds the minimum and maximum elements of " { $snippet "seq" } " in one pass. Throws an error on an empty sequence." }
 { $examples
     { $example "USING: arrays math.statistics prettyprint ;"
         "{ 1 2 3 } minmax 2array ."
index 73a87ffb72fe95f922d4f97fafaebc65ffe4e0af..c6a600a303555dcb30a5966623fcbc0dfde7d44f 100644 (file)
@@ -89,9 +89,14 @@ PRIVATE>
     histogram >alist
     [ ] [ [ [ second ] bi@ > ] 2keep ? ] map-reduce first ;
 
+ERROR: empty-sequence ;
+
 : minmax ( seq -- min max )
-    #! find the min and max of a seq in one pass
-    [ 1/0. -1/0. ] dip [ [ min ] [ max ] bi-curry bi* ] each ;
+    [
+        empty-sequence
+    ] [
+        [ first dup ] keep [ [ min ] [ max ] bi-curry bi* ] each
+    ] if-empty ;
 
 : range ( seq -- x )
     minmax swap - ;