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