better minmax

db4
Doug Coleman 2009-12-07 17:26:33 -06:00
parent 26de809d57
commit 8b38997e55
2 changed files with 8 additions and 3 deletions

View 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 ."

View 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 - ;