Commits

Sébastien Ferré committed 480722b

Add of 'flip': add an element if it is absent; remove it on the contrary.

Comments (0)

Files changed (1)

 (* test if a set is empty or not *)
 let is_empty : 'a list -> bool = function [] -> true | _ -> false
 
+(* return the cardinal of a set *)
+let cardinal : 'a list -> int = List.length
+
 (* return true if the first set contains the second *)
 let rec contains : 'a list -> 'a list -> bool =
   fun l1 l2 -> match l1, l2 with
       else if comp > 0 then false
       else contains l1 l2
 
+let mem : 'a -> 'a list -> bool =
+  fun x l -> contains l [x]
+
 (* return the union of 2 and several sets *)
 let rec union : 'a list -> 'a list -> 'a list =
   fun l1 l2 -> match l1, l2 with
 let union_r : 'a list list -> 'a list =
   fun sets -> List.fold_left (fun res set -> union res set) [] sets
 
+let add : 'a -> 'a list -> 'a list =
+  fun x l -> union [x] l
+
+let singleton : 'a -> 'a list =
+  fun x -> [x]
+
 (* return the intersection of 2 sets *)
 let rec inter : 'a list -> 'a list -> 'a list =
   fun l1 l2 -> match l1, l2 with
 let subtract_r : 'a list -> 'a list list -> 'a list =
   fun set sets -> List.fold_left (fun res set -> subtract res set) set sets
 
+let remove : 'a -> 'a list -> 'a list =
+  fun x l -> subtract l [x]
+
+let rec flip : 'a -> 'a list -> 'a list =
+  fun x -> function
+    [] -> [x]
+  | y::l ->
+      let comp = compare x y in
+      if comp < 0 then x::y::l
+      else if comp > 0 then y::flip x l
+      else l
+
 (*
    iterative functions on lists can also be applied, at least in some cases
 *)