forked from jrh13/hol-light
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metis.ml
10383 lines (8250 loc) · 331 KB
/
metis.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(* ========================================================================= *)
(* Metis first-order theorem proving derived rule/tactic for HOL Light. *)
(* *)
(* The original Metis was written by Joe Hurd, and it has been widely used *)
(* for first-order proofs in HOL4 and Isabelle; see: *)
(* *)
(* http://www.gilith.com/research/metis/ *)
(* *)
(* This is a port from SML to OCaml and proof-reconstructing integration *)
(* with HOL Light, written by Michael Faerber and Cezary Kaliszyk. *)
(* *)
(* (c) Copyright, Joe Hurd, 2001 *)
(* (c) Copyright, Joe Leslie-Hurd, 2004 *)
(* (c) Copyright, Michael Faerber and Cezary Kaliszyk, 2014-2018. *)
(* *)
(* Distributed under the same license as HOL Light. *)
(* ========================================================================= *)
needs "firstorder.ml";;
let metisverb = ref false;;
module Metis_prover = struct
(* ------------------------------------------------------------------------- *)
(* Convenient utility modules. *)
(* ------------------------------------------------------------------------- *)
module Portable = struct
let pointerEqual (p1, p2) = p1 == p2;;
let randomInt x = Random.int x;;
let randomWord () = Random.bits ();;
let critical x = x;;
end
module Option = struct
let getOpt = function
(Some s, _) -> s
| (None, x) -> x;;
let isSome = function
Some _ -> true
| None -> false;;
let mapPartial f = function
None -> None
| Some x -> f x;;
end
module Order = struct
type order = Less | Equal | Greater;;
let orderOfInt = function
-1 -> Less
| 0 -> Equal
| 1 -> Greater
| _ -> failwith "orderOfInt"
;;
let intOfOrder = function
Less -> -1
| Equal -> 0
| Greater -> 1
;;
let toCompare f = fun (x, y) -> orderOfInt (f x y);;
let fromCompare f = fun x y -> intOfOrder (f (x, y));;
end
module Int = struct
let toString = string_of_int;;
let compare = Order.toCompare (compare : int -> int -> int);;
let maxInt = Some max_int;;
let div x y = x / y;;
end
module Real = struct
open Order
type real = float;;
let compare = toCompare (compare : float -> float -> int);;
let fromInt = float_of_int;;
let floor x = int_of_float (floor x);;
end
(* ------------------------------------------------------------------------- *)
(* Emulating SML Word type (which is unsigned) and other operations. *)
(* ------------------------------------------------------------------------- *)
module Word = struct
open Order
type word = int;;
let compare = toCompare (compare: word -> word -> int);;
let shiftLeft (x, y) = x lsl y;;
let shiftRight (x, y) = x lsr y;;
(* This is only the same as the SML version, if there is no overflow *)
let minus (x,y) = x - y;;
let andb (x,y) = x land y;;
let orb (x,y) = x lor y;;
let xorb (x,y) = x lxor y;;
let notb x = lnot x
let toInt x = x;;
let fromInt x = x;;
end
module Math = struct
let ln = log;;
let pow (x,y) = x ** y;;
end
module Mlist = struct
let foldl f a l = List.fold_left (fun acc x -> f (x, acc)) a l;;
let foldr f a l = List.fold_right (fun x acc -> f (x, acc)) l a;;
let nth (l, i) = List.nth l i;;
let null = function
[] -> true
| _ -> false
let tabulate (n,f) =
let rec go i = if i == n then [] else f i :: go (i+1)
in go 0
let revAppend (l1, l2) = List.rev_append l1 l2;;
let find p l = try Some (List.find p l) with Not_found -> None;;
let all = List.for_all;;
end
(* ========================================================================= *)
(* ML UTILITY FUNCTIONS *)
(* ========================================================================= *)
module Useful = struct
open Order
(* ------------------------------------------------------------------------- *)
(* OCaml lists (MF). *)
(* ------------------------------------------------------------------------- *)
let length = List.length;;
let app = List.iter;;
(* ------------------------------------------------------------------------- *)
(* Characters (MF). *)
(* ------------------------------------------------------------------------- *)
let isDigit c = '0' <= c && c <= '9'
(* ------------------------------------------------------------------------- *)
(* Exceptions. *)
(* ------------------------------------------------------------------------- *)
exception Error of string;;
exception Bug of string;;
exception Subscript;;
let total f x = try Some (f x) with Error _ -> None;;
let isSome = function
(Some _) -> true
| None -> false
;;
let can f x = isSome (total f x);;
(* ------------------------------------------------------------------------- *)
(* Combinators. *)
(* ------------------------------------------------------------------------- *)
let cComb f x y = f y x;;
let iComb x = x;;
let kComb x y = x;;
let sComb f g x = f x (g x);;
let wComb f x = f x x;;
let rec funpow n f x = match n with
0 -> x
| _ -> funpow (n - 1) f (f x);;
let exp m =
let rec f x y z = match y with
0 -> z
| _ -> f (m (x,x)) (Int.div y 2) (if y mod 2 = 0 then z else m (z,x))
in
f
;;
(* ------------------------------------------------------------------------- *)
(* Pairs. *)
(* ------------------------------------------------------------------------- *)
let pair x y = (x,y);;
let swap (x,y) = (y,x);;
let curry f x y = f (x,y);;
let uncurry f (x,y) = f x y;;
(* ------------------------------------------------------------------------- *)
(* State transformers. *)
(* ------------------------------------------------------------------------- *)
let return : 'a -> 's -> 'a * 's = pair;;
let bind f (g : 'a -> 's -> 'b * 's) x = uncurry g (f x);;
(*fun mmap f (m : 's -> 'a * 's) = bind m (unit o f);
fun mjoin (f : 's -> ('s -> 'a * 's) * 's) = bind f I;
fun mwhile c b = let fun f a = if c a then bind (b a) f else unit a in f end;*)
(* ------------------------------------------------------------------------- *)
(* Comparisons. *)
(* ------------------------------------------------------------------------- *)
let revCompare cmp x_y =
match cmp x_y with Less -> Greater | Equal -> Equal | Greater -> Less;;
let prodCompare xCmp yCmp ((x1,y1),(x2,y2)) =
match xCmp (x1,x2) with
Less -> Less
| Equal -> yCmp (y1,y2)
| Greater -> Greater;;
let lexCompare cmp =
let rec lex = function
([],[]) -> Equal
| ([], _ :: _) -> Less
| (_ :: _, []) -> Greater
| (x :: xs, y :: ys) ->
(match cmp (x,y) with
Less -> Less
| Equal -> lex (xs,ys)
| Greater -> Greater)
in
lex
;;
let boolCompare = function
(false,true) -> Less
| (true,false) -> Greater
| _ -> Equal;;
(* ------------------------------------------------------------------------- *)
(* Lists. *)
(* ------------------------------------------------------------------------- *)
let rec first f = function
[] -> None
| (x :: xs) -> (match f x with None -> first f xs | s -> s);;
let rec maps (f : 'a -> 's -> 'b * 's) = function
[] -> return []
| (x :: xs) ->
bind (f x) (fun y -> bind (maps f xs) (fun ys -> return (y :: ys)));;
let zipWith f =
let rec z l = function
([], []) -> l
| (x :: xs, y :: ys) -> z (f x y :: l) (xs, ys)
| _ -> raise (Error "zipWith: lists different lengths")
in
fun xs -> fun ys -> List.rev (z [] (xs, ys))
;;
let zip xs ys = zipWith pair xs ys;;
let unzip ab =
let inc ((x,y),(xs,ys)) = (x :: xs, y :: ys)
in Mlist.foldl inc ([],[]) (List.rev ab);;
let enumerate l = fst (maps (fun x m -> ((m, x), m + 1)) l 0);;
let revDivide l =
let rec revDiv acc = function
(l, 0) -> (acc,l)
| ([], _) -> raise Subscript
| (h :: t, n) -> revDiv (h :: acc) (t, n - 1)
in fun n -> revDiv [] (l, n);;
let divide l n = let (a,b) = revDivide l n in (List.rev a, b);;
let updateNth (n,x) l =
let (a,b) = revDivide l n
in
match b with [] -> raise Subscript | (_ :: t) -> List.rev_append a (x :: t)
;;
let deleteNth n l =
let (a,b) = revDivide l n
in
match b with [] -> raise Subscript | (_ :: t) -> List.rev_append a t
;;
(* ------------------------------------------------------------------------- *)
(* Sets implemented with lists. *)
(* ------------------------------------------------------------------------- *)
let mem x l = List.mem x l;;
(* ------------------------------------------------------------------------- *)
(* Strings. *)
(* ------------------------------------------------------------------------- *)
let mkPrefix p s = p ^ s
let stripSuffix pred s =
let rec strip pos =
if pos < 0 then "" else
if pred (s.[pos]) then strip (pos - 1)
else String.sub s 0 (pos + 1)
in strip (String.length s - 1);;
(* ------------------------------------------------------------------------- *)
(* Sorting and searching. *)
(* ------------------------------------------------------------------------- *)
let sort cmp = List.sort (fromCompare cmp);;
let sortMap f cmp = function
[] -> []
| ([_] as l) -> l
| xs ->
let ncmp ((m,_),(n,_)) = cmp (m,n)
in let nxs = List.map (fun x -> (f x, x)) xs
in let nys = List.sort (fromCompare ncmp) nxs
in
List.map snd nys
;;
(* ------------------------------------------------------------------------- *)
(* Integers. *)
(* ------------------------------------------------------------------------- *)
let rec interval m = function
0 -> []
| len -> m :: interval (m + 1) (len - 1);;
let divides = function
(_, 0) -> true
| (0, _) -> false
| (a, b) -> b mod (abs a) = 0;;
let divides = curry divides;;
(* ------------------------------------------------------------------------- *)
(* Useful impure features. *)
(* ------------------------------------------------------------------------- *)
let generator = ref 0;;
let newIntThunk () =
let n = !generator
in generator := n + 1;
n
;;
let newIntsThunk k () =
let
n = !generator
in generator := n + k;
interval n k
;;
let newInt () = newIntThunk ();;
let newInts k =
if k <= 0 then []
else (newIntsThunk k) ();;
end
(* ========================================================================= *)
(* FINITE MAPS IMPLEMENTED WITH RANDOMLY BALANCED TREES *)
(* ========================================================================= *)
module Pmap = struct
open Order
(* ------------------------------------------------------------------------- *)
(* Importing useful functionality. *)
(* ------------------------------------------------------------------------- *)
exception Bug = Useful.Bug;;
exception Error = Useful.Error;;
let pointerEqual = Portable.pointerEqual;;
let kComb = Useful.kComb;;
let randomInt = Portable.randomInt;;
let randomWord = Portable.randomWord;;
(* ------------------------------------------------------------------------- *)
(* Converting a comparison function to an equality function. *)
(* ------------------------------------------------------------------------- *)
let equalKey compareKey key1 key2 = compareKey (key1,key2) = Equal;;
(* ------------------------------------------------------------------------- *)
(* Priorities. *)
(* ------------------------------------------------------------------------- *)
type priority = Word.word;;
let randomPriority = randomWord;;
let comparePriority = Word.compare;;
(* ------------------------------------------------------------------------- *)
(* Priority search trees. *)
(* ------------------------------------------------------------------------- *)
type ('key,'value) tree =
Empty
| Tree of ('key,'value) node
and ('key,'value) node =
{size : int;
priority : priority;
left : ('key,'value) tree;
key : 'key;
value : 'value;
right : ('key,'value) tree};;
let lowerPriorityNode node1 node2 =
let {priority = p1} = node1
and {priority = p2} = node2
in
comparePriority (p1,p2) = Less
;;
(* ------------------------------------------------------------------------- *)
(* Tree debugging functions. *)
(* ------------------------------------------------------------------------- *)
(*BasicDebug
local
let checkSizes tree =
match tree with
Empty -> 0
| Tree (Node {size,left,right,...}) ->
let
let l = checkSizes left
and r = checkSizes right
let () = if l + 1 + r = size then () else raise Bug "wrong size"
in
size
end;;
let checkSorted compareKey x tree =
match tree with
Empty -> x
| Tree (Node {left,key,right,...}) ->
let
let x = checkSorted compareKey x left
let () =
match x with
None -> ()
| Some k ->
match compareKey (k,key) with
Less -> ()
| Equal -> raise Bug "duplicate keys"
| Greater -> raise Bug "unsorted"
let x = Some key
in
checkSorted compareKey x right
end;;
let checkPriorities compareKey tree =
match tree with
Empty -> None
| Tree node ->
let
let Node {left,right,...} = node
let () =
match checkPriorities compareKey left with
None -> ()
| Some lnode ->
if not (lowerPriorityNode node lnode) then ()
else raise Bug "left child has greater priority"
let () =
match checkPriorities compareKey right with
None -> ()
| Some rnode ->
if not (lowerPriorityNode node rnode) then ()
else raise Bug "right child has greater priority"
in
Some node
end;;
in
let treeCheckInvariants compareKey tree =
let
let _ = checkSizes tree
let _ = checkSorted compareKey None tree
let _ = checkPriorities compareKey tree
in
tree
end
handle Error err -> raise (Bug err);;
end;;
*)
(* ------------------------------------------------------------------------- *)
(* Tree operations. *)
(* ------------------------------------------------------------------------- *)
let treeNew () = Empty;;
let nodeSize ({size = x}) = x;;
let treeSize tree =
match tree with
Empty -> 0
| Tree x -> nodeSize x;;
let mkNode priority left key value right =
let size = treeSize left + 1 + treeSize right
in
{size = size;
priority = priority;
left = left;
key = key;
value = value;
right = right}
;;
let mkTree priority left key value right =
let node = mkNode priority left key value right
in
Tree node
;;
(* ------------------------------------------------------------------------- *)
(* Extracting the left and right spines of a tree. *)
(* ------------------------------------------------------------------------- *)
let rec treeLeftSpine acc tree =
match tree with
Empty -> acc
| Tree node -> nodeLeftSpine acc node
and nodeLeftSpine acc node =
let {left=left} = node
in
treeLeftSpine (node :: acc) left
;;
let rec treeRightSpine acc tree =
match tree with
Empty -> acc
| Tree node -> nodeRightSpine acc node
and nodeRightSpine acc node =
let {right=right} = node
in
treeRightSpine (node :: acc) right
;;
(* ------------------------------------------------------------------------- *)
(* Singleton trees. *)
(* ------------------------------------------------------------------------- *)
let mkNodeSingleton priority key value =
let size = 1
and left = Empty
and right = Empty
in
{size = size;
priority = priority;
left = left;
key = key;
value = value;
right = right}
;;
let nodeSingleton (key,value) =
let priority = randomPriority ()
in
mkNodeSingleton priority key value
;;
let treeSingleton key_value =
let node = nodeSingleton key_value
in
Tree node
;;
(* ------------------------------------------------------------------------- *)
(* Appending two trees, where every element of the first tree is less than *)
(* every element of the second tree. *)
(* ------------------------------------------------------------------------- *)
let rec treeAppend tree1 tree2 =
match tree1 with
Empty -> tree2
| Tree node1 ->
match tree2 with
Empty -> tree1
| Tree node2 ->
if lowerPriorityNode node1 node2 then
let {priority=priority;left=left;key=key;value=value;right=right} = node2
in let left = treeAppend tree1 left
in
mkTree priority left key value right
else
let {priority=priority;left=left;key=key;value=value;right=right} = node1
in let right = treeAppend right tree2
in
mkTree priority left key value right
;;
(* ------------------------------------------------------------------------- *)
(* Appending two trees and a node, where every element of the first tree is *)
(* less than the node, which in turn is less than every element of the *)
(* second tree. *)
(* ------------------------------------------------------------------------- *)
let treeCombine left node right =
let left_node = treeAppend left (Tree node)
in
treeAppend left_node right
;;
(* ------------------------------------------------------------------------- *)
(* Searching a tree for a value. *)
(* ------------------------------------------------------------------------- *)
let rec treePeek compareKey pkey tree =
match tree with
Empty -> None
| Tree node -> nodePeek compareKey pkey node
and nodePeek compareKey pkey node =
let {left=left;key=key;value=value;right=right} = node
in
match compareKey (pkey,key) with
Less -> treePeek compareKey pkey left
| Equal -> Some value
| Greater -> treePeek compareKey pkey right
;;
(* ------------------------------------------------------------------------- *)
(* Tree paths. *)
(* ------------------------------------------------------------------------- *)
(* Generating a path by searching a tree for a key/value pair *)
let rec treePeekPath compareKey pkey path tree =
match tree with
Empty -> (path,None)
| Tree node -> nodePeekPath compareKey pkey path node
and nodePeekPath compareKey pkey path node =
let {left=left;key=key;right=right} = node
in
match compareKey (pkey,key) with
Less -> treePeekPath compareKey pkey ((true,node) :: path) left
| Equal -> (path, Some node)
| Greater -> treePeekPath compareKey pkey ((false,node) :: path) right
;;
(* A path splits a tree into left/right components *)
let addSidePath ((wentLeft,node),(leftTree,rightTree)) =
let {priority=priority;left=left;key=key;value=value;right=right} = node
in
if wentLeft then (leftTree, mkTree priority rightTree key value right)
else (mkTree priority left key value leftTree, rightTree)
;;
let addSidesPath left_right = Mlist.foldl addSidePath left_right;;
let mkSidesPath path = addSidesPath (Empty,Empty) path;;
(* Updating the subtree at a path *)
let updateTree ((wentLeft,node),tree) =
let {priority=priority;left=left;key=key;value=value;right=right} = node
in
if wentLeft then mkTree priority tree key value right
else mkTree priority left key value tree;;
let updateTreePath tree = Mlist.foldl updateTree tree;;
(* Inserting a new node at a path position *)
let insertNodePath node =
let rec insert left_right path =
match path with
[] ->
let (left,right) = left_right
in
treeCombine left node right
| ((_,snode) as step) :: rest ->
if lowerPriorityNode snode node then
let left_right = addSidePath (step,left_right)
in
insert left_right rest
else
let (left,right) = left_right
in let tree = treeCombine left node right
in
updateTreePath tree path
in
insert (Empty,Empty)
;;
(* ------------------------------------------------------------------------- *)
(* Using a key to split a node into three components: the keys comparing *)
(* less than the supplied key, an optional equal key, and the keys comparing *)
(* greater. *)
(* ------------------------------------------------------------------------- *)
let nodePartition compareKey pkey node =
let (path,pnode) = nodePeekPath compareKey pkey [] node
in
match pnode with
None ->
let (left,right) = mkSidesPath path
in
(left,None,right)
| Some node ->
let {left=left;key=key;value=value;right=right} = node
in let (left,right) = addSidesPath (left,right) path
in
(left, Some (key,value), right)
;;
(* ------------------------------------------------------------------------- *)
(* Searching a tree for a key/value pair. *)
(* ------------------------------------------------------------------------- *)
let rec treePeekKey compareKey pkey tree =
match tree with
Empty -> None
| Tree node -> nodePeekKey compareKey pkey node
and nodePeekKey compareKey pkey node =
let {left=left;key=key;value=value;right=right} = node
in
match compareKey (pkey,key) with
Less -> treePeekKey compareKey pkey left
| Equal -> Some (key,value)
| Greater -> treePeekKey compareKey pkey right
;;
(* ------------------------------------------------------------------------- *)
(* Inserting new key/values into the tree. *)
(* ------------------------------------------------------------------------- *)
let treeInsert compareKey key_value tree =
let (key,value) = key_value
in let (path,inode) = treePeekPath compareKey key [] tree
in
match inode with
None ->
let node = nodeSingleton (key,value)
in
insertNodePath node path
| Some node ->
let {size=size;priority=priority;left=left;right=right} = node
in let node =
{size = size;
priority = priority;
left = left;
key = key;
value = value;
right = right}
in
updateTreePath (Tree node) path
;;
(* ------------------------------------------------------------------------- *)
(* Deleting key/value pairs: it raises an exception if the supplied key is *)
(* not present. *)
(* ------------------------------------------------------------------------- *)
let rec treeDelete compareKey dkey tree =
match tree with
Empty -> raise (Bug "Map.delete: element not found")
| Tree node -> nodeDelete compareKey dkey node
and nodeDelete compareKey dkey node =
let {size=size;priority=priority;left=left;key=key;value=value;right=right} = node
in
match compareKey (dkey,key) with
Less ->
let size = size - 1
and left = treeDelete compareKey dkey left
in let node =
{size = size;
priority = priority;
left = left;
key = key;
value = value;
right = right}
in
Tree node
| Equal -> treeAppend left right
| Greater ->
let size = size - 1
and right = treeDelete compareKey dkey right
in let node =
{size = size;
priority = priority;
left = left;
key = key;
value = value;
right = right}
in
Tree node
;;
(* ------------------------------------------------------------------------- *)
(* Partial map is the basic operation for preserving tree structure. *)
(* It applies its argument function to the elements *in order*. *)
(* ------------------------------------------------------------------------- *)
let rec treeMapPartial f tree =
match tree with
Empty -> Empty
| Tree node -> nodeMapPartial f node
and nodeMapPartial f ({priority=priority;left=left;key=key;value=value;right=right}) =
let left = treeMapPartial f left
and vo = f (key,value)
and right = treeMapPartial f right
in
match vo with
None -> treeAppend left right
| Some value -> mkTree priority left key value right
;;
(* ------------------------------------------------------------------------- *)
(* Mapping tree values. *)
(* ------------------------------------------------------------------------- *)
let rec treeMap f tree =
match tree with
Empty -> Empty
| Tree node -> Tree (nodeMap f node)
and nodeMap f node =
let {size=size;priority=priority;left=left;key=key;value=value;right=right} = node
in let left = treeMap f left
and value = f (key,value)
and right = treeMap f right
in
{size = size;
priority = priority;
left = left;
key = key;
value = value;
right = right}
;;
(* ------------------------------------------------------------------------- *)
(* Merge is the basic operation for joining two trees. Note that the merged *)
(* key is always the one from the second map. *)
(* ------------------------------------------------------------------------- *)
let rec treeMerge compareKey f1 f2 fb tree1 tree2 =
match tree1 with
Empty -> treeMapPartial f2 tree2
| Tree node1 ->
match tree2 with
Empty -> treeMapPartial f1 tree1
| Tree node2 -> nodeMerge compareKey f1 f2 fb node1 node2
and nodeMerge compareKey f1 f2 fb node1 node2 =
let {priority=priority;left=left;key=key;value=value;right=right} = node2
in let (l,kvo,r) = nodePartition compareKey key node1
in let left = treeMerge compareKey f1 f2 fb l left
and right = treeMerge compareKey f1 f2 fb r right
in let vo =
match kvo with
None -> f2 (key,value)
| Some kv -> fb (kv,(key,value))
in
match vo with
None -> treeAppend left right
| Some value ->
let node = mkNodeSingleton priority key value
in
treeCombine left node right
;;
(* ------------------------------------------------------------------------- *)
(* A union operation on trees. *)
(* ------------------------------------------------------------------------- *)
let rec treeUnion compareKey f f2 tree1 tree2 =
match tree1 with
Empty -> tree2
| Tree node1 ->
match tree2 with
Empty -> tree1
| Tree node2 -> nodeUnion compareKey f f2 node1 node2
and nodeUnion compareKey f f2 node1 node2 =
if pointerEqual (node1,node2) then nodeMapPartial f2 node1
else
let {priority=priority;left=left;key=key;value=value;right=right} = node2
in let (l,kvo,r) = nodePartition compareKey key node1
in let left = treeUnion compareKey f f2 l left
and right = treeUnion compareKey f f2 r right
in let vo =
match kvo with
None -> Some value
| Some kv -> f (kv,(key,value))
in
match vo with
None -> treeAppend left right
| Some value ->
let node = mkNodeSingleton priority key value
in
treeCombine left node right
;;
(* ------------------------------------------------------------------------- *)
(* An intersect operation on trees. *)
(* ------------------------------------------------------------------------- *)
let rec treeIntersect compareKey f t1 t2 =
match t1 with
Empty -> Empty
| Tree n1 ->
match t2 with
Empty -> Empty
| Tree n2 -> nodeIntersect compareKey f n1 n2
and nodeIntersect compareKey f n1 n2 =
let {priority=priority;left=left;key=key;value=value;right=right} = n2
in let (l,kvo,r) = nodePartition compareKey key n1
in let left = treeIntersect compareKey f l left
and right = treeIntersect compareKey f r right
in let vo =
match kvo with