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