Skip to content
Browse files

[feature] libbase: choose_opt in Maps and Sets

Same as choose, but giving an option instead of an exception on empty map/set
  • Loading branch information...
1 parent 708e865 commit e74f6b52743214436ecfe923f3312c870c06123d Arthur Milchior committed with Mathieu Barbin Jun 28, 2011
Showing with 27 additions and 0 deletions.
  1. +4 −0 libbase/baseMap.ml
  2. +5 −0 libbase/baseMapSig.ml
  3. +4 −0 libbase/baseSet.ml
  4. +5 −0 libbase/baseSetSig.ml
  5. +3 −0 libbase/intMap.ml
  6. +6 −0 libbase/intSet.ml
View
4 libbase/baseMap.ml
@@ -576,6 +576,10 @@ struct
add k v acc
) map1 empty
+ let rec choose_opt = function
+ | Empty -> None
+ | Node(_, k, v, _r, _) -> Some (k, v)
+
let from_sorted_array keys vals =
let len_keys = Array.length keys in
let len_vals = Array.length vals in
View
5 libbase/baseMapSig.ml
@@ -80,6 +80,11 @@ sig
@raise Not_found on the empty list
*)
val choose : 'a t -> (key * 'a)
+
+ (**
+ Returns an arbitrary element of the set if it is not_empty, or null
+ *)
+ val choose_opt : 'a t -> (key * 'a) option
val map : ('a -> 'b) -> 'a t -> 'b t
val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
val fold_map : (key -> 'a -> 'c -> 'c * 'b) -> 'a t -> 'c -> 'c * 'b t
View
4 libbase/baseSet.ml
@@ -321,6 +321,10 @@ struct
let choose = min_elt
+ let rec choose_opt = function
+ | Empty -> None
+ | Node (_, v, _r, _) -> Some v
+
let complete_join big small =
fold add small big
View
5 libbase/baseSetSig.ml
@@ -62,6 +62,11 @@ sig
@raise Not_found on the empty set
*)
val choose : t -> elt
+
+ (**
+ Returns an arbitrary element of the set if it is not empty
+ *)
+ val choose_opt : t -> elt option
val split : elt -> t -> t * bool * t
val draw : t -> elt * t
val size : t -> int
View
3 libbase/intMap.ml
@@ -338,6 +338,9 @@ let min t = ordertop min t
*)
let choose = min
+let choose_opt t =
+ try Some (choose t) with | Not_found -> None
+
let rec max t = match t with
| Br (_,_m,_tl,tr) -> max tr
| Lf (k,v) -> k,v
View
6 libbase/intSet.ml
@@ -70,6 +70,12 @@ let diff set set' = filter (fun x -> not (mem x set')) set
let subset (set:t) (set':t) = for_all (fun x -> mem x set') set
let choose = min_elt
+
+let choose_opt (set:t) =
+ match IntMap.choose_opt set with
+ | None -> None
+ | Some (a, _) -> Some a
+
let split int set =
fold
(fun i (inf, b, sup) ->

0 comments on commit e74f6b5

Please sign in to comment.
Something went wrong with that request. Please try again.