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 let acc = ref acc in
seq (fun elt -> let acc' = f !acc elt in k acc'; acc := acc')) seq (fun elt -> let acc' = f !acc elt in k acc'; acc := acc'))
(** Max element of the sequence, using the given comparison let max ?(lt=fun x y -> x < y) seq =
function. A default element has to be provided. *) let ret = ref None in
let max ?(lt=fun x y -> x < y) seq m = seq (fun x -> match !ret with
fold (fun m x -> if lt m x then x else m) m seq | 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 =
let min ?(lt=fun x y -> x < y) seq m = let ret = ref None in
fold (fun m x -> if lt x m then x else m) m seq seq (fun x -> match !ret with
| None -> ret := Some x
| Some y -> if lt x y then ret := Some x);
!ret
exception ExitSequence 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 val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t
(** Sequence of intermediate results *) (** Sequence of intermediate results *)
val max : ?lt:('a -> 'a -> bool) -> 'a t -> 'a -> 'a val max : ?lt:('a -> 'a -> bool) -> 'a t -> 'a option
(** Max element of the sequence, using the given comparison (** Max element of the sequence, using the given comparison function.
function. A default element has to be provided. *) @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 val min : ?lt:('a -> 'a -> bool) -> 'a t -> 'a option
(** Min element of the sequence, using the given comparison function *) (** Min element of the sequence, using the given comparison function.
see {!max} for more details. *)
val take : int -> 'a t -> 'a t val take : int -> 'a t -> 'a t
(** Take at most [n] elements from the sequence. Works on infinite (** Take at most [n] elements from the sequence. Works on infinite