change the interface of min/max so that they return an option

in case the sequence is empty
This commit is contained in:
Simon Cruanes 2014-04-16 17:39:32 +02:00
parent 7d5d7a497f
commit 2d380a48ca
2 changed files with 19 additions and 12 deletions

View file

@ -313,14 +313,19 @@ let scan f acc seq =
let acc = ref acc in
seq (fun elt -> let acc' = f !acc elt in k acc'; acc := acc'))
(** Max element of the sequence, using the given comparison
function. A default element has to be provided. *)
let max ?(lt=fun x y -> x < y) seq m =
fold (fun m x -> if lt m x then x else m) m seq
let max ?(lt=fun x y -> x < y) seq =
let ret = ref None in
seq (fun x -> match !ret with
| None -> ret := Some x
| Some y -> if lt y x then ret := Some x);
!ret
(** Min element of the sequence, using the given comparison function *)
let min ?(lt=fun x y -> x < y) seq m =
fold (fun m x -> if lt x m then x else m) m seq
let min ?(lt=fun x y -> x < y) seq =
let ret = ref None in
seq (fun x -> match !ret with
| None -> ret := Some x
| Some y -> if lt x y then ret := Some x);
!ret
exception ExitSequence

View file

@ -191,12 +191,14 @@ val unfoldr : ('b -> ('a * 'b) option) -> 'b -> 'a t
val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t
(** Sequence of intermediate results *)
val max : ?lt:('a -> 'a -> bool) -> 'a t -> 'a -> 'a
(** Max element of the sequence, using the given comparison
function. A default element has to be provided. *)
val max : ?lt:('a -> 'a -> bool) -> 'a t -> 'a option
(** Max element of the sequence, using the given comparison function.
@return None if the sequence is empty, Some [m] where [m] is the maximal
element otherwise *)
val min : ?lt:('a -> 'a -> bool) -> 'a t -> 'a -> 'a
(** Min element of the sequence, using the given comparison function *)
val min : ?lt:('a -> 'a -> bool) -> 'a t -> 'a option
(** Min element of the sequence, using the given comparison function.
see {!max} for more details. *)
val take : int -> 'a t -> 'a t
(** Take at most [n] elements from the sequence. Works on infinite