Skip to content

Commit

Permalink
[feature] libbase: choose_opt in Maps and Sets
Browse files Browse the repository at this point in the history
Same as choose, but giving an option instead of an exception on empty map/set
  • Loading branch information
Arthur Milchior authored and Mathieu Barbin committed Jul 11, 2011
1 parent 708e865 commit e74f6b5
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 0 deletions.
4 changes: 4 additions & 0 deletions libbase/baseMap.ml
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions libbase/baseMapSig.ml
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions libbase/baseSet.ml
Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions libbase/baseSetSig.ml
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions libbase/intMap.ml
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions libbase/intSet.ml
Expand Up @@ -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) ->
Expand Down

0 comments on commit e74f6b5

Please sign in to comment.