Source

ocaml-lib / dietset.ml

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
(***********************************************************************)
(*                                                                     *)
(*  Sebastien Ferre                                                    *)
(*                                                                     *)
(*  Copyright 2005 Universite de Rennes 1.  All rights reserved.       *)
(*  This file is distributed under the terms of the GNU Library        *)
(*  General Public License.                                            *)
(*                                                                     *)
(***********************************************************************)

(* Diet sets over ordered types with succ and pred operations *)

module type OrderedType =
  sig
    type t
    val compare: t -> t -> int
    val succ: t -> t
    val pred: t -> t
    val size: t -> t -> int
  end

module type S =
  sig
    type elt
    type t
    val empty: t
    val is_empty: t -> bool
    val mem: elt -> t -> bool
    val add: elt -> t -> t
    val singleton: elt -> t
    val remove: elt -> t -> t
    val union: t -> t -> t
    val inter: t -> t -> t
    val diff: t -> t -> t
    val compare: t -> t -> int
    val equal: t -> t -> bool
    val subset: t -> t -> bool
    val iter: (elt -> unit) -> t -> unit
    val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a
    val for_all: (elt -> bool) -> t -> bool
    val exists: (elt -> bool) -> t -> bool
    val filter: (elt -> bool) -> t -> t
    val partition: (elt -> bool) -> t -> t * t
    val cardinal: t -> int
    val elements: t -> elt list
    val min_elt: t -> elt
    val max_elt: t -> elt
    val choose: t -> elt
    val split: elt -> t -> t * bool * t
  end

module Make(Ord: OrderedType) =
  struct
    type elt = Ord.t
    type t = Empty | Node of t * elt * elt * t * int

    let lt x y = Ord.compare x y < 0
    let le x y = Ord.compare x y <= 0
    let gt x y = Ord.compare x y > 0
    let eq x y = Ord.compare x y = 0

    (* Diet Sets are represented by balanced binary trees (the heights of the
       children differ by at most 2 *)

    let height = function
        Empty -> 0
      | Node(_, _, _, _, h) -> h

    (* Creates a new node with left son l, interval x y and right son r.
       We must have all elements of l < x <= y < all elements of r.
       l and r must be balanced and | height l - height r | <= 2.
       Inline expansion of height for better speed. *)

    let create l x y r =
      let hl = match l with Empty -> 0 | Node(_,_,_,_,h) -> h in
      let hr = match r with Empty -> 0 | Node(_,_,_,_,h) -> h in
      Node(l, x, y, r, (if hl >= hr then hl + 1 else hr + 1))

    (* Same as create, but performs one step of rebalancing if necessary.
       Assumes l and r balanced and | height l - height r | <= 3.
       Inline expansion of create for better speed in the most frequent case
       where no rebalancing is required. *)

    let bal l x y r =
      let hl = match l with Empty -> 0 | Node(_,_,_,_,h) -> h in
      let hr = match r with Empty -> 0 | Node(_,_,_,_,h) -> h in
      if hl > hr + 2 then begin
        match l with
          Empty -> invalid_arg "Set.bal"
        | Node(ll, lx, ly, lr, _) ->
            if height ll >= height lr then
              create ll lx ly (create lr x y r)
            else begin
              match lr with
                Empty -> invalid_arg "Set.bal"
              | Node(lrl, lrx, lry, lrr, _)->
                  create (create ll lx ly lrl) lrx lry (create lrr x y r)
            end
      end else if hr > hl + 2 then begin
        match r with
          Empty -> invalid_arg "Set.bal"
        | Node(rl, rx, ry, rr, _) ->
            if height rr >= height rl then
              create (create l x y rl) rx ry rr
            else begin
              match rl with
                Empty -> invalid_arg "Set.bal"
              | Node(rll, rlx, rly, rlr, _) ->
                  create (create l x y rll) rlx rly (create rlr rx ry rr)
            end
      end else
        Node(l, x, y, r, (if hl >= hr then hl + 1 else hr + 1))

    (* Returns the rightmost interval, and the tree less this interval *)

    let rec split_max = function
      | Node (l, x, y, Empty, _) ->
	  (x, y, l)
      | Node (l, x, y, r, _) ->
	  let (u, v, r') = split_max r in
	  (u, v, bal l x y r')
      | Empty -> invalid_arg "Dietset.split_max"

    (* Joins the root to its left interval, if necessary. *)

    let rec join_left = function
      | Empty as t -> t
      | Node (Empty, _, _, _, _) as t -> t
      | Node (l, x, y, r, _) as t ->
	  let (x', y', l') = split_max l in
	  if le (Ord.pred x) y'
	  then
	    if lt x x'
	    then join_left (create l' x y r)
	    else bal l' x' y r
	  else t

    (* Returns the leftmost interval, and the tree less this interval. *)

    let rec split_min = function
      | Node (Empty, x, y, r, _) ->
	  (x, y, r)
      | Node (l, x, y, r, _) ->
	  let (u, v, l') = split_min l in
	  (u, v, bal l' x y r)
      | Empty -> invalid_arg "Dietset.split_min"

    (* Joins the root to its right interval, if necessary. *)

    let rec join_right = function
      | Empty as t -> t
      | Node (_, _, _, Empty, _) as t -> t
      | Node (l, x, y, r, _) as t ->
	  let (x', y', r') = split_min r in
	  if le x' (Ord.succ y)
	  then
	    if lt y' y
	    then join_right (create l x y r') 
	    else bal l x y' r'
	  else t

    (* Insertion of an interval *)

    let rec add_interv x0 y0 = function
        Empty ->
	  Node(Empty, x0, y0, Empty, 1)
      | Node(l, x, y, r, h) as t ->
	  if lt y0 (Ord.pred x) then
	    bal (add_interv x0 y0 l) x y r
	  else if lt (Ord.succ y) x0 then
	    bal l x y (add_interv x0 y0 r)
	  else
	    if lt x0 x
	    then
	      if lt y y0
	      then join_left (join_right (Node(l,x0,y0,r,h)))
	      else join_left (Node(l,x0,y,r,h))
	    else
	      if lt y y0
	      then join_right (Node(l,x,y0,r,h))
	      else t

    (* Same as create and bal, but no assumptions are made on the
       relative heights of l and r. *)

    let rec join l x y r =
      match (l, r) with
        (Empty, _) -> add_interv x y r
      | (_, Empty) -> add_interv x y l
      | (Node(ll, lx, ly, lr, lh), Node(rl, rx, ry, rr, rh)) ->
          if lh > rh + 2 then bal ll lx ly (join lr x y r) else
          if rh > lh + 2 then bal (join l x y rl) rx ry rr else
          create l x y r

    (* Smallest and greatest element of a set *)

    let rec min_elt = function
        Empty -> raise Not_found
      | Node(Empty, x, y, r, _) -> x
      | Node(l, x, y, r, _) -> min_elt l

    let rec max_elt = function
        Empty -> raise Not_found
      | Node(l, x, y, Empty, _) -> y
      | Node(l, x, y, r, _) -> max_elt r

    (* Merge two trees l and r into one.
       All elements of l must precede the elements of r.
       Assume | height l - height r | <= 2. *)

    let merge t1 t2 =
      match (t1, t2) with
        (Empty, t) -> t
      | (t, Empty) -> t
      | (_, _) ->
	  let u, v, t2' = split_min t2 in
	  bal t1 u v t2'

    (* Merge two trees l and r into one.
       All elements of l must precede the elements of r.
       No assumption on the heights of l and r. *)

    let concat t1 t2 =
      match (t1, t2) with
        (Empty, t) -> t
      | (t, Empty) -> t
      | (_, _) ->
	  let u, v, t2' = split_min t2 in
	  join t1 u v t2'

    (* Splitting.  split x s returns a triple (l, present, r) where
        - l is the set of elements of s that are < x
        - r is the set of elements of s that are > x
        - present is false if s contains no element equal to x,
          or true if s contains an element equal to x. *)

    let rec split f e x0 y0 = function
        Empty ->
          (Empty, e, Empty)
      | Node(l, x, y, r, _) ->
	  if lt y x0 then (* node on the left of (x0,y0) *)
	    (* x <= y < x0 <= y0 *)
	    let (rl,e',rr) = split f e x0 y0 r in
	    (create l x y rl, e', rr)
	  else if lt y0 x then (* node on the right of (x0,y0) *)
	    (* x0 <= y0 < x <= y *)
	    let (ll,e',lr) = split f e x0 y0 l in
	    (ll, e', create lr x y r)
	  else (* (x,y) and (x0,y0) overlap *)
	    if lt x x0 then (* every node on the left of (x,y) is on the left of (x0,y0) *)
	      if lt y0 y then (* every node on the right of (x,y) is on the right of (x0,y0) *)
		(* x < x0 <= y0 < y *)
		(create l x (Ord.pred x0) Empty, f x0 y0 e, create Empty (Ord.succ y0) y r)
	      else begin
		(* x < x0 <= y <= y0 *)
		let (rl,e',rr) = split f e x0 y0 r in (* rl must be empty *)
		(create l x (Ord.pred x0) Empty, f x0 y e', rr) end
	    else
	      if lt y0 y then begin (* every node on the right of (x,y) is on the right of (x0,y0) *)
		(* x0 <= x <= y0 < y *)
		let (ll,e',lr) = split f e x0 y0 l in (* lr must be empty *)
		(ll, f x y0 e', create Empty (Ord.succ y0) y r) end
	      else begin
		(* x0 <= x <= y <= y0 *)
		let (ll,e',lr) = split f e x0 y0 l in (* lr must be empty *)
		let (rl,e'',rr) = split f e' x0 y0 r in (* rl must be empty *)
		(ll, f x y e'', rr) end

    (* Implementation of the set operations *)

    let empty = Empty

    let is_empty = function Empty -> true | _ -> false

    let rec mem v = function
        Empty -> false
      | Node(l, x, y, r, _) ->
	  (* trick: (pred x) and (succ x) are not in the set *)
	  let c1 = Ord.compare v (Ord.pred x) in
	  if c1 < 0 then mem v l
	  else
	    let c2 = Ord.compare (Ord.succ y) v in
	    if c2 < 0 then mem v r
	    else c1 > 0 & c2 > 0

    let singleton v = Node(Empty, v, v, Empty, 1)

    let add v s = add_interv v v s

    let rec remove v = function
        Empty -> Empty
      | Node(l, x, y, r, h) as t ->
	  (* trick: (pred x) and (succ x) are not in the set *)
	  let c1 = Ord.compare v (Ord.pred x) in
	  if c1 < 0 then bal (remove v l) x y r
	  else
	    let c2 = Ord.compare (Ord.succ y) v in
	    if c2 < 0 then bal l x y (remove v r)
	    else if c1 > 0 & c2 > 0 then
	      if eq v x then
		if eq x y
		then merge l r
		else Node(l,Ord.succ x,y,r,h)
	      else (* lt x v *)
		if eq v y
		then Node(l,x,Ord.pred y,r,h)
		else join l x (Ord.pred v) (create Empty (Ord.succ v) y r)
	    else t

    let rec union2 s1 s2 =
      match s1, s2 with
      | (Empty, t2) -> t2
      | (t1, Empty) -> t1
      | (t1, Node(l2, x2, y2, r2, _)) ->
	  union2 (add_interv x2 y2 (union2 t1 l2)) r2

    let f_union x y () = () (*min x u, max y v*)
    let rec union =
      fun s1 s2 ->
	match (s1, s2) with
          (Empty, t2) -> t2
	| (t1, Empty) -> t1
	| (Node(l1, x1, y1, r1, h1), Node(l2, x2, y2, r2, h2)) ->
            if h1 >= h2 then
              if h2 = 1 then add_interv x2 y2 s1
	      else begin
		let (l2, _, r2) = split f_union () x1 y1 s2 in
		(*match*) join_right (join_left (create (union l1 l2) x1 y1 (union r1 r2))) (*with
		| Node (l, x, y, r, _) -> join l x y r
		| Empty -> assert false*) end
            else
              if h1 = 1 then add_interv x1 y1 s2
	      else begin
		let (l1, _, r1) = split f_union () x2 y2 s1 in
		(*match*) join_right (join_left (create (union l1 l2) x2 y2 (union r1 r2))) (*with
		| Node (l, x, y, r, _) -> join l x y r
		| Empty -> assert false*) end

    let f_inter x y t : t = add_interv x y t
    let rec inter =
      fun s1 s2 ->
	match (s1, s2) with
          (Empty, t2) -> Empty
	| (t1, Empty) -> Empty
	| (Node(l1, x1, y1, r1, _), t2) ->
	    let (l2, m2, r2) = split f_inter Empty x1 y1 t2 in
	    merge (inter l1 l2) (merge m2 (inter r1 r2))

    let f_diff x y () = ()
    let rec diff =
      fun s1 s2 ->
	match (s1, s2) with
          (Empty, t2) -> Empty
	| (t1, Empty) -> t1
	| (t1, Node(l2, x2, y2, r2, _)) ->
	    let (l1, _, r1) = split f_diff () x2 y2 t1 in
	    concat (diff l1 l2) (diff r1 r2)

    let rec subset s1 s2 =
      match (s1, s2) with
        Empty, _ ->
          true
      | _, Empty ->
          false
      | Node (l1, x1, y1, r1, _), (Node (l2, x2, y2, r2, _) as t2) ->
	  if le x2 x1 & le y1 y2 then
	    (* x2 <= x1 <= y1 <= y2 *)
	    subset l1 (Node (l2, x2, x1, Empty, 0)) & subset r1 (Node (Empty, y1, y2, r2, 0))
	  else if lt y2 (Ord.pred x1) then
	    (* x2 <= y2 < pred x1 <= y1 *)
	    subset l1 t2 & subset (Node (Empty, x1, y1, r1, 0)) r2
	  else if lt (Ord.succ y1) x2 then
	    (* x1 <= succ y1 < x2 <= y2 *)
	    subset (Node (l1, x1, y1, Empty, 0)) l2 & subset r1 t2
	  else
	    false

    let rec iter_interv f x y =
      if le x y then begin f x; iter_interv f (Ord.succ x) y end

    let rec iter f = function
        Empty -> ()
      | Node(l, x, y, r, _) -> iter f l; iter_interv f x y; iter f r

    let rec fold_right_interv f x y accu =
      if le x y
      then fold_right_interv f x (Ord.pred y) (f y accu)
      else accu

    let rec fold_right f s accu =
      match s with
        Empty -> accu
      | Node(l, x, y, r, _) -> fold_right f l (fold_right_interv f x y (fold_right f r accu))

    let rec fold_left_interv f accu x y =
      if le x y
      then fold_left_interv f (Ord.succ x) y (f accu x)
      else accu

    let rec fold_left f accu s =
      match s with
        Empty -> accu
      | Node(l, x, y, r, _) -> fold_left f (fold_left_interv f (fold_left f accu l) x y) l

(* TODO

    let rec for_all p = function
        Empty -> true
      | Node(l, x, y, r, _) -> p v && for_all p l && for_all p r

    let rec exists p = function
        Empty -> false
      | Node(l, v, r, _) -> p v || exists p l || exists p r

    let filter p s =
      let rec filt accu = function
        | Empty -> accu
        | Node(l, v, r, _) ->
            filt (filt (if p v then add v accu else accu) l) r in
      filt Empty s

    let partition p s =
      let rec part (t, f as accu) = function
        | Empty -> accu
        | Node(l, v, r, _) ->
            part (part (if p v then (add v t, f) else (t, add v f)) l) r in
      part (Empty, Empty) s

TODO *)

    let rec cardinal = function
        Empty -> 0
      | Node(l, x, y, r, _) -> cardinal l + Ord.size x y + cardinal r

    let from_list l =
      List.fold_left (fun res x -> add x res) empty l

    let elements s =
      fold_right (fun x xs -> x::xs) s []

    let choose = min_elt

  end

module OrdInt =
  struct
    type t = int
    let compare = compare
    let succ = succ
    let pred = pred
    let size x y = y - x + 1
  end

module OSet = Set.Make(OrdInt)

let set_of_list l =
  List.fold_left (fun res x -> OSet.add x res) OSet.empty l;;

module DietSet = Make(OrdInt)


(* test section *)

#load "nums.cma"
#load "str.cma"
#load "unix.cma"
#load "common.cmo"
#load "lSet.cmo"

let print_lset l =
  List.iter (fun x -> print_int x; print_string " ") l;
  print_newline ()

let print_prof s =
  try
    let n, t, m = Hashtbl.find Common.tbl_prof s in
    print_int n; print_string "\t";
    print_float t; print_string "\t";
    print_float m; print_string "\n"
  with _ -> print_endline (s ^ " cannot be found in profiling")

let rec random_list range =
  function
    | 0 -> []
    | len ->
	let x = Random.int range in
	x::random_list range (len-1)

let rec test range len1 len2 n =
  Hashtbl.clear Common.tbl_prof;
  for i = 1 to n do
    let l1 = random_list range len1 in
    let ls1 = LSet.of_list l1 in
    let os1 = set_of_list l1 in
    let ds1 = DietSet.from_list l1 in
    let l2 = random_list range len2 in
    let ls2 = LSet.of_list l2 in
    let os2 = set_of_list l2 in
    let ds2 = DietSet.from_list l2 in
    let ls = Common.prof "lset" (fun () -> LSet.union ls1 ls2) in
    let os = Common.prof "oset" (fun () -> OSet.union os1 os2) in
    let ds = Common.prof "dietset" (fun () -> DietSet.union ds1 ds2) in
    if DietSet.elements ds <> ls
    then begin
      print_lset ls1;
      print_lset ls2;
      print_lset ls;
      print_lset (DietSet.elements ds);
      raise Not_found end
  done;
  print_prof "lset";
  print_prof "oset";
  print_prof "dietset"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.