From 2d380a48caca6f12aaea1ff6179f9c10de27774d Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Wed, 16 Apr 2014 17:39:32 +0200 Subject: [PATCH] change the interface of min/max so that they return an option in case the sequence is empty --- sequence.ml | 19 ++++++++++++------- sequence.mli | 12 +++++++----- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/sequence.ml b/sequence.ml index d0cf59e..0823cd0 100644 --- a/sequence.ml +++ b/sequence.ml @@ -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 diff --git a/sequence.mli b/sequence.mli index 697a5d3..e9c4574 100644 --- a/sequence.mli +++ b/sequence.mli @@ -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