diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 434d240a..5799d71e 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -797,6 +797,19 @@ let is_sorted ~cmp l = is_sorted ~cmp:CCInt.compare (List.sort Stdlib.compare l)) *) +let rec sorted_mem ~cmp x l = match l with + | [] -> false + | y :: tail -> + match cmp x y with + | 0 -> true + | n when n<0 -> false + | _ -> (sorted_mem[@tailcall]) ~cmp x tail + +(*$Q + Q.(pair small_int (list small_int)) (fun (x,l) -> \ + sorted_mem ~cmp:CCInt.compare x (List.sort CCInt.compare l) = mem ~eq:CCInt.equal x l) +*) + let sorted_insert ~cmp ?(uniq=false) x l = let rec aux cmp uniq x left l = match l with | [] -> List.rev_append left [x] diff --git a/src/core/CCList.mli b/src/core/CCList.mli index 91148e24..28c39213 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -523,6 +523,10 @@ val is_sorted : cmp:('a -> 'a -> int) -> 'a list -> bool @param cmp the comparison function. @since 0.17 *) +val sorted_mem : cmp:('a -> 'a -> int) -> 'a -> 'a list -> bool +(** Suppose the list [l] is sorted. [sorted_mem x l] is [true] iff [x] is equal to an element of [l]. + @since NEXT_RELEASE *) + val sorted_insert : cmp:('a -> 'a -> int) -> ?uniq:bool -> 'a -> 'a list -> 'a list (** [sorted_insert ~cmp ?uniq x l] inserts [x] into [l] such that, if [l] was sorted, then [sorted_insert x l] is sorted too. diff --git a/src/core/CCListLabels.mli b/src/core/CCListLabels.mli index bca4cc6a..5085b320 100644 --- a/src/core/CCListLabels.mli +++ b/src/core/CCListLabels.mli @@ -526,6 +526,10 @@ val is_sorted : cmp:(('a -> 'a -> int) [@keep_label]) -> 'a list -> bool @param cmp the comparison function. @since 0.17 *) +val sorted_mem : cmp:(('a -> 'a -> int) [@keep_label]) -> 'a -> 'a list -> bool +(** Suppose the list [l] is sorted. [sorted_mem x l] is [true] iff [x] is equal to an element of [l]. + @since NEXT_RELEASE *) + val sorted_insert : cmp:(('a -> 'a -> int) [@keep_label]) -> ?uniq:bool -> 'a -> 'a list -> 'a list (** [sorted_insert ~cmp ?uniq x l] inserts [x] into [l] such that, if [l] was sorted, then [sorted_insert x l] is sorted too.