feat(CCSet): add find_first_map and find_last_map

This commit is contained in:
Fardale 2023-02-16 12:23:14 +01:00
parent 53f2ffca9f
commit e6611f1920
2 changed files with 45 additions and 0 deletions

View file

@ -34,6 +34,11 @@ module type S = sig
(** Safe version of {!find_first}.
@since 1.5 *)
val find_first_map : (elt -> 'a option) -> t -> 'a option
(** [find_first_map f s] find the minimum element [x] of [s] such that [f x = Some y]
and return [Some y]. Otherwise returns [None].
@since NEXT_RELEASE *)
val find_last : (elt -> bool) -> t -> elt
(** Find maximum element satisfying predicate.
@since 1.5 *)
@ -42,6 +47,11 @@ module type S = sig
(** Safe version of {!find_last}.
@since 1.5 *)
val find_last_map : (elt -> 'a option) -> t -> 'a option
(** [find_last_map f s] find the maximum element [x] of [s] such that [f x = Some y]
and return [Some y]. Otherwise returns [None].
@since NEXT_RELEASE *)
val of_iter : elt iter -> t
(** Build a set from the given [iter] of elements.
@since 2.8 *)
@ -116,6 +126,20 @@ module Make (O : Map.OrderedType) = struct
| None -> raise Not_found
| Some x -> x
let find_first_map f m =
let res = ref None in
try
S.iter
(fun x ->
match f x with
| None -> ()
| Some y ->
res := Some y;
raise Find_binding_exit)
m;
None
with Find_binding_exit -> !res
(* linear time, must traverse the whole set… *)
let find_last_opt f m =
let res = ref None in
@ -127,6 +151,17 @@ module Make (O : Map.OrderedType) = struct
| None -> raise Not_found
| Some x -> x
(* linear time, must traverse the whole set… *)
let find_last_map f m =
let res = ref None in
S.iter
(fun x ->
match f x with
| None -> ()
| Some y -> res := Some y)
m;
!res
include S
let add_seq seq set =

View file

@ -40,6 +40,11 @@ module type S = sig
(** Safe version of {!find_first}.
@since 1.5 *)
val find_first_map : (elt -> 'a option) -> t -> 'a option
(** [find_first_map f s] find the minimum element [x] of [s] such that [f x = Some y]
and return [Some y]. Otherwise returns [None].
@since NEXT_RELEASE *)
val find_last : (elt -> bool) -> t -> elt
(** Find maximum element satisfying predicate.
@since 1.5 *)
@ -48,6 +53,11 @@ module type S = sig
(** Safe version of {!find_last}.
@since 1.5 *)
val find_last_map : (elt -> 'a option) -> t -> 'a option
(** [find_last_map f s] find the maximum element [x] of [s] such that [f x = Some y]
and return [Some y]. Otherwise returns [None].
@since NEXT_RELEASE *)
val of_iter : elt iter -> t
(** Build a set from the given [iter] of elements.
@since 2.8 *)