-
Notifications
You must be signed in to change notification settings - Fork 251
/
Ordnode.lean
1355 lines (1117 loc) · 48.9 KB
/
Ordnode.lean
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
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Order.Compare
import Mathlib.Data.List.Defs
import Mathlib.Data.Nat.PSub
import Mathlib.Data.Option.Basic
#align_import data.ordmap.ordnode from "leanprover-community/mathlib"@"dd71334db81d0bd444af1ee339a29298bef40734"
/-!
# Ordered sets
This file defines a data structure for ordered sets, supporting a
variety of useful operations including insertion and deletion,
logarithmic time lookup, set operations, folds,
and conversion from lists.
The `Ordnode α` operations all assume that `α` has the structure of
a total preorder, meaning a `≤` operation that is
* Transitive: `x ≤ y → y ≤ z → x ≤ z`
* Reflexive: `x ≤ x`
* Total: `x ≤ y ∨ y ≤ x`
For example, in order to use this data structure as a map type, one
can store pairs `(k, v)` where `(k, v) ≤ (k', v')` is defined to mean
`k ≤ k'` (assuming that the key values are linearly ordered).
Two values `x,y` are equivalent if `x ≤ y` and `y ≤ x`. An `Ordnode α`
maintains the invariant that it never stores two equivalent nodes;
the insertion operation comes with two variants depending on whether
you want to keep the old value or the new value in case you insert a value
that is equivalent to one in the set.
The operations in this file are not verified, in the sense that they provide
"raw operations" that work for programming purposes but the invariants
are not explicitly in the structure. See `Ordset` for a verified version
of this data structure.
## Main definitions
* `Ordnode α`: A set of values of type `α`
## Implementation notes
Based on weight balanced trees:
* Stephen Adams, "Efficient sets: a balancing act",
Journal of Functional Programming 3(4):553-562, October 1993,
<http://www.swiss.ai.mit.edu/~adams/BB/>.
* J. Nievergelt and E.M. Reingold,
"Binary search trees of bounded balance",
SIAM journal of computing 2(1), March 1973.
Ported from Haskell's `Data.Set`.
## Tags
ordered map, ordered set, data structure
-/
universe u
/-- An `Ordnode α` is a finite set of values, represented as a tree.
The operations on this type maintain that the tree is balanced
and correctly stores subtree sizes at each level. -/
inductive Ordnode (α : Type u) : Type u
| nil : Ordnode α
| node (size : ℕ) (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α
#align ordnode Ordnode
-- Porting note: `Nat.Partrec.Code.recOn` is noncomputable in Lean4, so we make it computable.
compile_inductive% Ordnode
namespace Ordnode
variable {α : Type*}
instance : EmptyCollection (Ordnode α) :=
⟨nil⟩
instance : Inhabited (Ordnode α) :=
⟨nil⟩
/-- **Internal use only**
The maximal relative difference between the sizes of
two trees, it corresponds with the `w` in Adams' paper.
According to the Haskell comment, only `(delta, ratio)` settings
of `(3, 2)` and `(4, 2)` will work, and the proofs in
`Ordset.lean` assume `delta := 3` and `ratio := 2`. -/
@[inline]
def delta :=
3
#align ordnode.delta Ordnode.delta
/-- **Internal use only**
The ratio between an outer and inner sibling of the
heavier subtree in an unbalanced setting. It determines
whether a double or single rotation should be performed
to restore balance. It is corresponds with the inverse
of `α` in Adam's article. -/
@[inline]
def ratio :=
2
#align ordnode.ratio Ordnode.ratio
/-- O(1). Construct a singleton set containing value `a`.
singleton 3 = {3} -/
@[inline]
protected def singleton (a : α) : Ordnode α :=
node 1 nil a nil
#align ordnode.singleton Ordnode.singleton
local prefix:arg "ι" => Ordnode.singleton
instance : Singleton α (Ordnode α) :=
⟨Ordnode.singleton⟩
/-- O(1). Get the size of the set.
size {2, 1, 1, 4} = 3 -/
@[inline]
def size : Ordnode α → ℕ
| nil => 0
| node sz _ _ _ => sz
#align ordnode.size Ordnode.size
-- Porting note(#11647): during the port we marked these lemmas with `@[eqns]`
-- to emulate the old Lean 3 behaviour.
@[simp] theorem size_nil : size (nil : Ordnode α) = 0 :=
rfl
@[simp] theorem size_node (sz : ℕ) (l : Ordnode α) (x : α) (r : Ordnode α) :
size (node sz l x r) = sz :=
rfl
/-- O(1). Is the set empty?
empty ∅ = tt
empty {1, 2, 3} = ff -/
@[inline]
def empty : Ordnode α → Bool
| nil => true
| node _ _ _ _ => false
#align ordnode.empty Ordnode.empty
/-- **Internal use only**, because it violates the BST property on the original order.
O(n). The dual of a tree is a tree with its left and right sides reversed throughout.
The dual of a valid BST is valid under the dual order. This is convenient for exploiting
symmetries in the algorithms. -/
@[simp]
def dual : Ordnode α → Ordnode α
| nil => nil
| node s l x r => node s (dual r) x (dual l)
#align ordnode.dual Ordnode.dual
/-- **Internal use only**
O(1). Construct a node with the correct size information, without rebalancing. -/
@[inline, reducible]
def node' (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α :=
node (size l + size r + 1) l x r
#align ordnode.node' Ordnode.node'
/-- Basic pretty printing for `Ordnode α` that shows the structure of the tree.
repr {3, 1, 2, 4} = ((∅ 1 ∅) 2 ((∅ 3 ∅) 4 ∅)) -/
def repr {α} [Repr α] (o : Ordnode α) (n : ℕ) : Std.Format :=
match o with
| nil => (Std.Format.text "∅")
| node _ l x r =>
let fmt := Std.Format.joinSep
[repr l n, Repr.reprPrec x n, repr r n]
" "
Std.Format.paren fmt
#align ordnode.repr Ordnode.repr
instance {α} [Repr α] : Repr (Ordnode α) :=
⟨repr⟩
-- Note: The function has been written with tactics to avoid extra junk
/-- **Internal use only**
O(1). Rebalance a tree which was previously balanced but has had its left
side grow by 1, or its right side shrink by 1. -/
def balanceL (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α := by
-- Porting note: removed `clean`
cases' id r with rs
· cases' id l with ls ll lx lr
· exact ι x
· cases' id ll with lls
· cases' lr with _ _ lrx
· exact node 2 l x nil
· exact node 3 (ι lx) lrx ι x
· cases' id lr with lrs lrl lrx lrr
· exact node 3 ll lx ι x
· exact
if lrs < ratio * lls then node (ls + 1) ll lx (node (lrs + 1) lr x nil)
else
node (ls + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + 1) lrr x nil)
· cases' id l with ls ll lx lr
· exact node (rs + 1) nil x r
· refine if ls > delta * rs then ?_ else node (ls + rs + 1) l x r
cases' id ll with lls
· exact nil
--should not happen
cases' id lr with lrs lrl lrx lrr
· exact nil
--should not happen
exact
if lrs < ratio * lls then node (ls + rs + 1) ll lx (node (rs + lrs + 1) lr x r)
else
node (ls + rs + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + rs + 1) lrr x r)
#align ordnode.balance_l Ordnode.balanceL
/-- **Internal use only**
O(1). Rebalance a tree which was previously balanced but has had its right
side grow by 1, or its left side shrink by 1. -/
def balanceR (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α := by
-- Porting note: removed `clean`
cases' id l with ls
· cases' id r with rs rl rx rr
· exact ι x
· cases' id rr with rrs
· cases' rl with _ _ rlx
· exact node 2 nil x r
· exact node 3 (ι x) rlx ι rx
· cases' id rl with rls rll rlx rlr
· exact node 3 (ι x) rx rr
· exact
if rls < ratio * rrs then node (rs + 1) (node (rls + 1) nil x rl) rx rr
else
node (rs + 1) (node (size rll + 1) nil x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
· cases' id r with rs rl rx rr
· exact node (ls + 1) l x nil
· refine if rs > delta * ls then ?_ else node (ls + rs + 1) l x r
cases' id rr with rrs
· exact nil
--should not happen
cases' id rl with rls rll rlx rlr
· exact nil
--should not happen
exact
if rls < ratio * rrs then node (ls + rs + 1) (node (ls + rls + 1) l x rl) rx rr
else
node (ls + rs + 1) (node (ls + size rll + 1) l x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
#align ordnode.balance_r Ordnode.balanceR
/-- **Internal use only**
O(1). Rebalance a tree which was previously balanced but has had one side change
by at most 1. -/
def balance (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α := by
-- Porting note: removed `clean`
cases' id l with ls ll lx lr
· cases' id r with rs rl rx rr
· exact ι x
· cases' id rl with rls rll rlx rlr
· cases id rr
· exact node 2 nil x r
· exact node 3 (ι x) rx rr
· cases' id rr with rrs
· exact node 3 (ι x) rlx ι rx
· exact
if rls < ratio * rrs then node (rs + 1) (node (rls + 1) nil x rl) rx rr
else
node (rs + 1) (node (size rll + 1) nil x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
· cases' id r with rs rl rx rr
· cases' id ll with lls
· cases' lr with _ _ lrx
· exact node 2 l x nil
· exact node 3 (ι lx) lrx ι x
· cases' id lr with lrs lrl lrx lrr
· exact node 3 ll lx ι x
· exact
if lrs < ratio * lls then node (ls + 1) ll lx (node (lrs + 1) lr x nil)
else
node (ls + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + 1) lrr x nil)
· refine
if delta * ls < rs then ?_ else if delta * rs < ls then ?_ else node (ls + rs + 1) l x r
· cases' id rl with rls rll rlx rlr
· exact nil
--should not happen
cases' id rr with rrs
· exact nil
--should not happen
exact
if rls < ratio * rrs then node (ls + rs + 1) (node (ls + rls + 1) l x rl) rx rr
else
node (ls + rs + 1) (node (ls + size rll + 1) l x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
· cases' id ll with lls
· exact nil
--should not happen
cases' id lr with lrs lrl lrx lrr
· exact nil
--should not happen
exact
if lrs < ratio * lls then node (ls + rs + 1) ll lx (node (lrs + rs + 1) lr x r)
else
node (ls + rs + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + rs + 1) lrr x r)
#align ordnode.balance Ordnode.balance
/-- O(n). Does every element of the map satisfy property `P`?
All (fun x ↦ x < 5) {1, 2, 3} = True
All (fun x ↦ x < 5) {1, 2, 3, 5} = False -/
def All (P : α → Prop) : Ordnode α → Prop
| nil => True
| node _ l x r => All P l ∧ P x ∧ All P r
#align ordnode.all Ordnode.All
instance All.decidable {P : α → Prop} : (t : Ordnode α) → [DecidablePred P] → Decidable (All P t)
| nil => decidableTrue
| node _ l _ r =>
have : Decidable (All P l) := All.decidable l
have : Decidable (All P r) := All.decidable r
And.decidable
#align ordnode.all.decidable Ordnode.All.decidable
/-- O(n). Does any element of the map satisfy property `P`?
Any (fun x ↦ x < 2) {1, 2, 3} = True
Any (fun x ↦ x < 2) {2, 3, 5} = False -/
def Any (P : α → Prop) : Ordnode α → Prop
| nil => False
| node _ l x r => Any P l ∨ P x ∨ Any P r
#align ordnode.any Ordnode.Any
instance Any.decidable {P : α → Prop} : (t : Ordnode α ) → [DecidablePred P] → Decidable (Any P t)
| nil => decidableFalse
| node _ l _ r =>
have : Decidable (Any P l) := Any.decidable l
have : Decidable (Any P r) := Any.decidable r
Or.decidable
#align ordnode.any.decidable Ordnode.Any.decidable
/-- O(n). Exact membership in the set. This is useful primarily for stating
correctness properties; use `∈` for a version that actually uses the BST property
of the tree.
Emem 2 {1, 2, 3} = true
Emem 4 {1, 2, 3} = false -/
def Emem (x : α) : Ordnode α → Prop :=
Any (Eq x)
#align ordnode.emem Ordnode.Emem
instance Emem.decidable (x : α) [DecidableEq α] : ∀ t, Decidable (Emem x t) := by
dsimp [Emem]; infer_instance
#align ordnode.emem.decidable Ordnode.Emem.decidable
/-- O(n). Approximate membership in the set, that is, whether some element in the
set is equivalent to this one in the preorder. This is useful primarily for stating
correctness properties; use `∈` for a version that actually uses the BST property
of the tree.
Amem 2 {1, 2, 3} = true
Amem 4 {1, 2, 3} = false
To see the difference with `Emem`, we need a preorder that is not a partial order.
For example, suppose we compare pairs of numbers using only their first coordinate. Then:
-- Porting note: Verify below example
emem (0, 1) {(0, 0), (1, 2)} = false
amem (0, 1) {(0, 0), (1, 2)} = true
(0, 1) ∈ {(0, 0), (1, 2)} = true
The `∈` relation is equivalent to `Amem` as long as the `Ordnode` is well formed,
and should always be used instead of `Amem`. -/
def Amem [LE α] (x : α) : Ordnode α → Prop :=
Any fun y => x ≤ y ∧ y ≤ x
#align ordnode.amem Ordnode.Amem
instance Amem.decidable [LE α] [@DecidableRel α (· ≤ ·)] (x : α) :
∀ t, Decidable (Amem x t) := by
dsimp [Amem]; infer_instance
#align ordnode.amem.decidable Ordnode.Amem.decidable
/-- O(log n). Return the minimum element of the tree, or the provided default value.
findMin' 37 {1, 2, 3} = 1
findMin' 37 ∅ = 37 -/
def findMin' : Ordnode α → α → α
| nil, x => x
| node _ l x _, _ => findMin' l x
#align ordnode.find_min' Ordnode.findMin'
/-- O(log n). Return the minimum element of the tree, if it exists.
findMin {1, 2, 3} = some 1
findMin ∅ = none -/
def findMin : Ordnode α → Option α
| nil => none
| node _ l x _ => some (findMin' l x)
#align ordnode.find_min Ordnode.findMin
/-- O(log n). Return the maximum element of the tree, or the provided default value.
findMax' 37 {1, 2, 3} = 3
findMax' 37 ∅ = 37 -/
def findMax' : α → Ordnode α → α
| x, nil => x
| _, node _ _ x r => findMax' x r
#align ordnode.find_max' Ordnode.findMax'
/-- O(log n). Return the maximum element of the tree, if it exists.
findMax {1, 2, 3} = some 3
findMax ∅ = none -/
def findMax : Ordnode α → Option α
| nil => none
| node _ _ x r => some (findMax' x r)
#align ordnode.find_max Ordnode.findMax
/-- O(log n). Remove the minimum element from the tree, or do nothing if it is already empty.
eraseMin {1, 2, 3} = {2, 3}
eraseMin ∅ = ∅ -/
def eraseMin : Ordnode α → Ordnode α
| nil => nil
| node _ nil _ r => r
| node _ (node sz l' y r') x r => balanceR (eraseMin (node sz l' y r')) x r
#align ordnode.erase_min Ordnode.eraseMin
/-- O(log n). Remove the maximum element from the tree, or do nothing if it is already empty.
eraseMax {1, 2, 3} = {1, 2}
eraseMax ∅ = ∅ -/
def eraseMax : Ordnode α → Ordnode α
| nil => nil
| node _ l _ nil => l
| node _ l x (node sz l' y r') => balanceL l x (eraseMax (node sz l' y r'))
#align ordnode.erase_max Ordnode.eraseMax
/-- **Internal use only**, because it requires a balancing constraint on the inputs.
O(log n). Extract and remove the minimum element from a nonempty tree. -/
def splitMin' : Ordnode α → α → Ordnode α → α × Ordnode α
| nil, x, r => (x, r)
| node _ ll lx lr, x, r =>
let (xm, l') := splitMin' ll lx lr
(xm, balanceR l' x r)
#align ordnode.split_min' Ordnode.splitMin'
/-- O(log n). Extract and remove the minimum element from the tree, if it exists.
split_min {1, 2, 3} = some (1, {2, 3})
split_min ∅ = none -/
def splitMin : Ordnode α → Option (α × Ordnode α)
| nil => none
| node _ l x r => splitMin' l x r
#align ordnode.split_min Ordnode.splitMin
/-- **Internal use only**, because it requires a balancing constraint on the inputs.
O(log n). Extract and remove the maximum element from a nonempty tree. -/
def splitMax' : Ordnode α → α → Ordnode α → Ordnode α × α
| l, x, nil => (l, x)
| l, x, node _ rl rx rr =>
let (r', xm) := splitMax' rl rx rr
(balanceL l x r', xm)
#align ordnode.split_max' Ordnode.splitMax'
/-- O(log n). Extract and remove the maximum element from the tree, if it exists.
split_max {1, 2, 3} = some ({1, 2}, 3)
split_max ∅ = none -/
def splitMax : Ordnode α → Option (Ordnode α × α)
| nil => none
| node _ x l r => splitMax' x l r
#align ordnode.split_max Ordnode.splitMax
/-- **Internal use only**
O(log(m + n)). Concatenate two trees that are balanced and ordered with respect to each other. -/
def glue : Ordnode α → Ordnode α → Ordnode α
| nil, r => r
| l@(node _ _ _ _), nil => l
| l@(node sl ll lx lr), r@(node sr rl rx rr) =>
if sl > sr then
let (l', m) := splitMax' ll lx lr
balanceR l' m r
else
let (m, r') := splitMin' rl rx rr
balanceL l m r'
#align ordnode.glue Ordnode.glue
/-- O(log(m + n)). Concatenate two trees that are ordered with respect to each other.
merge {1, 2} {3, 4} = {1, 2, 3, 4}
merge {3, 4} {1, 2} = precondition violation -/
def merge (l : Ordnode α) : Ordnode α → Ordnode α :=
(Ordnode.recOn (motive := fun _ => Ordnode α → Ordnode α) l fun r => r)
fun ls ll lx lr _ IHlr r =>
(Ordnode.recOn (motive := fun _ => Ordnode α) r (node ls ll lx lr))
fun rs rl rx rr IHrl _ =>
if delta * ls < rs then balanceL IHrl rx rr
else
if delta * rs < ls then balanceR ll lx (IHlr <| node rs rl rx rr)
else glue (node ls ll lx lr) (node rs rl rx rr)
#align ordnode.merge Ordnode.merge
/-- O(log n). Insert an element above all the others, without any comparisons.
(Assumes that the element is in fact above all the others).
insertMax {1, 2} 4 = {1, 2, 4}
insertMax {1, 2} 0 = precondition violation -/
def insertMax : Ordnode α → α → Ordnode α
| nil, x => ι x
| node _ l y r, x => balanceR l y (insertMax r x)
#align ordnode.insert_max Ordnode.insertMax
/-- O(log n). Insert an element below all the others, without any comparisons.
(Assumes that the element is in fact below all the others).
insertMin {1, 2} 0 = {0, 1, 2}
insertMin {1, 2} 4 = precondition violation -/
def insertMin (x : α) : Ordnode α → Ordnode α
| nil => ι x
| node _ l y r => balanceR (insertMin x l) y r
#align ordnode.insert_min Ordnode.insertMin
/-- O(log(m+n)). Build a tree from an element between two trees, without any
assumption on the relative sizes.
link {1, 2} 4 {5, 6} = {1, 2, 4, 5, 6}
link {1, 3} 2 {5} = precondition violation -/
def link (l : Ordnode α) (x : α) : Ordnode α → Ordnode α :=
-- Porting note: Previous code was:
-- (Ordnode.recOn l (insertMin x)) fun ls ll lx lr IHll IHlr r =>
-- (Ordnode.recOn r (insertMax l x)) fun rs rl rx rr IHrl IHrr =>
-- if delta * ls < rs then balanceL IHrl rx rr
-- else if delta * rs < ls then balanceR ll lx (IHlr r) else node' l x r
--
-- failed to elaborate eliminator, expected type is not available.
match l with
| nil => insertMin x
| node ls ll lx lr => fun r ↦
match r with
| nil => insertMax l x
| node rs rl rx rr =>
if delta * ls < rs then balanceL (link ll x rl) rx rr
else if delta * rs < ls then balanceR ll lx (link lr x rr)
else node' l x r
#align ordnode.link Ordnode.link
/-- O(n). Filter the elements of a tree satisfying a predicate.
filter (fun x ↦ x < 3) {1, 2, 4} = {1, 2}
filter (fun x ↦ x > 5) {1, 2, 4} = ∅ -/
def filter (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α
| nil => nil
| node _ l x r => if p x then
link (filter p l) x (filter p r) else
merge (filter p l) (filter p r)
#align ordnode.filter Ordnode.filter
/-- O(n). Split the elements of a tree into those satisfying, and not satisfying, a predicate.
partition (fun x ↦ x < 3) {1, 2, 4} = ({1, 2}, {3}) -/
def partition (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α × Ordnode α
| nil => (nil, nil)
| node _ l x r =>
let (l₁, l₂) := partition p l
let (r₁, r₂) := partition p r
if p x then (link l₁ x r₁, merge l₂ r₂) else (merge l₁ r₁, link l₂ x r₂)
#align ordnode.partition Ordnode.partition
/- warning: ordnode.map -> Ordnode.map is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}}, (α -> β) -> (Ordnode.{u1} α) -> (Ordnode.{u2} β)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}}, (α -> β) -> (Ordnode.{u2} α) -> (Ordnode.{u1} β)
Case conversion may be inaccurate. Consider using '#align ordnode.map Ordnode.mapₓ'. -/
/-- O(n). Map a function across a tree, without changing the structure. Only valid when
the function is strictly monotone, i.e. `x < y → f x < f y`.
partition (fun x ↦ x + 2) {1, 2, 4} = {2, 3, 6}
partition (fun x : ℕ ↦ x - 2) {1, 2, 4} = precondition violation -/
def map {β} (f : α → β) : Ordnode α → Ordnode β
| nil => nil
| node s l x r => node s (map f l) (f x) (map f r)
#align ordnode.map Ordnode.map
/- warning: ordnode.fold -> Ordnode.fold is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Sort.{u2}}, β -> (β -> α -> β -> β) -> (Ordnode.{u1} α) -> β
but is expected to have type
forall {α : Type.{u2}} {β : Sort.{u1}}, β -> (β -> α -> β -> β) -> (Ordnode.{u2} α) -> β
Case conversion may be inaccurate. Consider using '#align ordnode.fold Ordnode.foldₓ'. -/
/-- O(n). Fold a function across the structure of a tree.
fold z f {1, 2, 4} = f (f z 1 z) 2 (f z 4 z)
The exact structure of function applications depends on the tree and so
is unspecified. -/
def fold {β} (z : β) (f : β → α → β → β) : Ordnode α → β
| nil => z
| node _ l x r => f (fold z f l) x (fold z f r)
#align ordnode.fold Ordnode.fold
/- warning: ordnode.foldl -> Ordnode.foldl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Sort.{u2}}, (β -> α -> β) -> β -> (Ordnode.{u1} α) -> β
but is expected to have type
forall {α : Type.{u2}} {β : Sort.{u1}}, (β -> α -> β) -> β -> (Ordnode.{u2} α) -> β
Case conversion may be inaccurate. Consider using '#align ordnode.foldl Ordnode.foldlₓ'. -/
/-- O(n). Fold a function from left to right (in increasing order) across the tree.
foldl f z {1, 2, 4} = f (f (f z 1) 2) 4 -/
def foldl {β} (f : β → α → β) : β → Ordnode α → β
| z, nil => z
| z, node _ l x r => foldl f (f (foldl f z l) x) r
#align ordnode.foldl Ordnode.foldl
/- warning: ordnode.foldr -> Ordnode.foldr is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Sort.{u2}}, (α -> β -> β) -> (Ordnode.{u1} α) -> β -> β
but is expected to have type
forall {α : Type.{u2}} {β : Sort.{u1}}, (α -> β -> β) -> (Ordnode.{u2} α) -> β -> β
Case conversion may be inaccurate. Consider using '#align ordnode.foldr Ordnode.foldrₓ'. -/
/-- O(n). Fold a function from right to left (in decreasing order) across the tree.
foldr f {1, 2, 4} z = f 1 (f 2 (f 4 z)) -/
def foldr {β} (f : α → β → β) : Ordnode α → β → β
| nil, z => z
| node _ l x r, z => foldr f l (f x (foldr f r z))
#align ordnode.foldr Ordnode.foldr
/-- O(n). Build a list of elements in ascending order from the tree.
toList {1, 2, 4} = [1, 2, 4]
toList {2, 1, 1, 4} = [1, 2, 4] -/
def toList (t : Ordnode α) : List α :=
foldr List.cons t []
#align ordnode.to_list Ordnode.toList
/-- O(n). Build a list of elements in descending order from the tree.
toRevList {1, 2, 4} = [4, 2, 1]
toRevList {2, 1, 1, 4} = [4, 2, 1] -/
def toRevList (t : Ordnode α) : List α :=
foldl (flip List.cons) [] t
#align ordnode.to_rev_list Ordnode.toRevList
instance [ToString α] : ToString (Ordnode α) :=
⟨fun t => "{" ++ String.intercalate ", " (t.toList.map toString) ++ "}"⟩
-- Porting note removed unsafe
instance [Std.ToFormat α] : Std.ToFormat (Ordnode α) where
format := fun t => Std.Format.joinSep (t.toList.map Std.ToFormat.format) (Std.Format.text ", ")
/-- O(n). True if the trees have the same elements, ignoring structural differences.
Equiv {1, 2, 4} {2, 1, 1, 4} = true
Equiv {1, 2, 4} {1, 2, 3} = false -/
def Equiv (t₁ t₂ : Ordnode α) : Prop :=
t₁.size = t₂.size ∧ t₁.toList = t₂.toList
#align ordnode.equiv Ordnode.Equiv
instance [DecidableEq α] : DecidableRel (@Equiv α) := fun _ _ => And.decidable
/-- O(2^n). Constructs the powerset of a given set, that is, the set of all subsets.
powerset {1, 2, 3} = {∅, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}} -/
def powerset (t : Ordnode α) : Ordnode (Ordnode α) :=
insertMin nil <| foldr (fun x ts => glue (insertMin (ι x) (map (insertMin x) ts)) ts) t nil
#align ordnode.powerset Ordnode.powerset
/-- O(m * n). The cartesian product of two sets: `(a, b) ∈ s.prod t` iff `a ∈ s` and `b ∈ t`.
prod {1, 2} {2, 3} = {(1, 2), (1, 3), (2, 2), (2, 3)} -/
protected def prod {β} (t₁ : Ordnode α) (t₂ : Ordnode β) : Ordnode (α × β) :=
fold nil (fun s₁ a s₂ => merge s₁ <| merge (map (Prod.mk a) t₂) s₂) t₁
#align ordnode.prod Ordnode.prod
/-- O(m + n). Build a set on the disjoint union by combining sets on the factors.
`Or.inl a ∈ s.copair t` iff `a ∈ s`, and `Or.inr b ∈ s.copair t` iff `b ∈ t`.
copair {1, 2} {2, 3} = {inl 1, inl 2, inr 2, inr 3} -/
protected def copair {β} (t₁ : Ordnode α) (t₂ : Ordnode β) : Ordnode (Sum α β) :=
merge (map Sum.inl t₁) (map Sum.inr t₂)
#align ordnode.copair Ordnode.copair
/- warning: ordnode.pmap -> Ordnode.pmap is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {P : α -> Prop} {β : Type.{u2}}, (forall (a : α), (P a) -> β) ->
(forall (t : Ordnode.{u1} α), (Ordnode.All.{u1} α P t) -> (Ordnode.{u2} β))
but is expected to have type
forall {α : Type.{u2}} {P : α -> Prop} {β : Type.{u1}}, (forall (a : α), (P a) -> β) ->
(forall (t : Ordnode.{u2} α), (Ordnode.All.{u2} α P t) -> (Ordnode.{u1} β))S
Case conversion may be inaccurate. Consider using '#align ordnode.pmap Ordnode.pmapₓ'. -/
/-- O(n). Map a partial function across a set. The result depends on a proof
that the function is defined on all members of the set.
pmap (fin.mk : ∀ n, n < 4 → fin 4) {1, 2} H = {(1 : fin 4), (2 : fin 4)} -/
def pmap {P : α → Prop} {β} (f : ∀ a, P a → β) : ∀ t : Ordnode α, All P t → Ordnode β
| nil, _ => nil
| node s l x r, ⟨hl, hx, hr⟩ => node s (pmap f l hl) (f x hx) (pmap f r hr)
#align ordnode.pmap Ordnode.pmap
/-- O(n). "Attach" the information that every element of `t` satisfies property
P to these elements inside the set, producing a set in the subtype.
attach' (fun x ↦ x < 4) {1, 2} H = ({1, 2} : Ordnode {x // x<4}) -/
def attach' {P : α → Prop} : ∀ t, All P t → Ordnode { a // P a } :=
pmap Subtype.mk
#align ordnode.attach' Ordnode.attach'
/-- O(log n). Get the `i`th element of the set, by its index from left to right.
nth {a, b, c, d} 2 = some c
nth {a, b, c, d} 5 = none -/
def nth : Ordnode α → ℕ → Option α
| nil, _ => none
| node _ l x r, i =>
match Nat.psub' i (size l) with
| none => nth l i
| some 0 => some x
| some (j + 1) => nth r j
#align ordnode.nth Ordnode.nth
/-- O(log n). Remove the `i`th element of the set, by its index from left to right.
remove_nth {a, b, c, d} 2 = {a, b, d}
remove_nth {a, b, c, d} 5 = {a, b, c, d} -/
def removeNth : Ordnode α → ℕ → Ordnode α
| nil, _ => nil
| node _ l x r, i =>
match Nat.psub' i (size l) with
| none => balanceR (removeNth l i) x r
| some 0 => glue l r
| some (j + 1) => balanceL l x (removeNth r j)
#align ordnode.remove_nth Ordnode.removeNth
/-- Auxiliary definition for `take`. (Can also be used in lieu of `take` if you know the
index is within the range of the data structure.)
takeAux {a, b, c, d} 2 = {a, b}
takeAux {a, b, c, d} 5 = {a, b, c, d} -/
def takeAux : Ordnode α → ℕ → Ordnode α
| nil, _ => nil
| node _ l x r, i =>
if i = 0 then nil
else
match Nat.psub' i (size l) with
| none => takeAux l i
| some 0 => l
| some (j + 1) => link l x (takeAux r j)
#align ordnode.take_aux Ordnode.takeAux
/-- O(log n). Get the first `i` elements of the set, counted from the left.
take 2 {a, b, c, d} = {a, b}
take 5 {a, b, c, d} = {a, b, c, d} -/
def take (i : ℕ) (t : Ordnode α) : Ordnode α :=
if size t ≤ i then t else takeAux t i
#align ordnode.take Ordnode.take
/-- Auxiliary definition for `drop`. (Can also be used in lieu of `drop` if you know the
index is within the range of the data structure.)
drop_aux {a, b, c, d} 2 = {c, d}
drop_aux {a, b, c, d} 5 = ∅ -/
def dropAux : Ordnode α → ℕ → Ordnode α
| nil, _ => nil
| t@(node _ l x r), i =>
if i = 0 then t
else
match Nat.psub' i (size l) with
| none => link (dropAux l i) x r
| some 0 => insertMin x r
| some (j + 1) => dropAux r j
#align ordnode.drop_aux Ordnode.dropAux
/-- O(log n). Remove the first `i` elements of the set, counted from the left.
drop 2 {a, b, c, d} = {c, d}
drop 5 {a, b, c, d} = ∅ -/
def drop (i : ℕ) (t : Ordnode α) : Ordnode α :=
if size t ≤ i then nil else dropAux t i
#align ordnode.drop Ordnode.drop
/-- Auxiliary definition for `splitAt`. (Can also be used in lieu of `splitAt` if you know the
index is within the range of the data structure.)
splitAtAux {a, b, c, d} 2 = ({a, b}, {c, d})
splitAtAux {a, b, c, d} 5 = ({a, b, c, d}, ∅) -/
def splitAtAux : Ordnode α → ℕ → Ordnode α × Ordnode α
| nil, _ => (nil, nil)
| t@(node _ l x r), i =>
if i = 0 then (nil, t)
else
match Nat.psub' i (size l) with
| none =>
let (l₁, l₂) := splitAtAux l i
(l₁, link l₂ x r)
| some 0 => (glue l r, insertMin x r)
| some (j + 1) =>
let (r₁, r₂) := splitAtAux r j
(link l x r₁, r₂)
#align ordnode.split_at_aux Ordnode.splitAtAux
/-- O(log n). Split a set at the `i`th element, getting the first `i` and everything else.
splitAt 2 {a, b, c, d} = ({a, b}, {c, d})
splitAt 5 {a, b, c, d} = ({a, b, c, d}, ∅) -/
def splitAt (i : ℕ) (t : Ordnode α) : Ordnode α × Ordnode α :=
if size t ≤ i then (t, nil) else splitAtAux t i
#align ordnode.split_at Ordnode.splitAt
/-- O(log n). Get an initial segment of the set that satisfies the predicate `p`.
`p` is required to be antitone, that is, `x < y → p y → p x`.
takeWhile (fun x ↦ x < 4) {1, 2, 3, 4, 5} = {1, 2, 3}
takeWhile (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/
def takeWhile (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α
| nil => nil
| node _ l x r => if p x then link l x (takeWhile p r) else takeWhile p l
#align ordnode.take_while Ordnode.takeWhile
/-- O(log n). Remove an initial segment of the set that satisfies the predicate `p`.
`p` is required to be antitone, that is, `x < y → p y → p x`.
dropWhile (fun x ↦ x < 4) {1, 2, 3, 4, 5} = {4, 5}
dropWhile (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/
def dropWhile (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α
| nil => nil
| node _ l x r => if p x then dropWhile p r else link (dropWhile p l) x r
#align ordnode.drop_while Ordnode.dropWhile
/-- O(log n). Split the set into those satisfying and not satisfying the predicate `p`.
`p` is required to be antitone, that is, `x < y → p y → p x`.
span (fun x ↦ x < 4) {1, 2, 3, 4, 5} = ({1, 2, 3}, {4, 5})
span (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/
def span (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α × Ordnode α
| nil => (nil, nil)
| node _ l x r =>
if p x then
let (r₁, r₂) := span p r
(link l x r₁, r₂)
else
let (l₁, l₂) := span p l
(l₁, link l₂ x r)
#align ordnode.span Ordnode.span
/-- Auxiliary definition for `ofAscList`.
**Note:** This function is defined by well founded recursion, so it will probably not compute
in the kernel, meaning that you probably can't prove things like
`ofAscList [1, 2, 3] = {1, 2, 3}` by `rfl`.
This implementation is optimized for VM evaluation. -/
def ofAscListAux₁ : ∀ l : List α, ℕ → Ordnode α × { l' : List α // l'.length ≤ l.length }
| [] => fun _ => (nil, ⟨[], le_rfl⟩)
| x :: xs => fun s =>
if s = 1 then (ι x, ⟨xs, Nat.le_succ _⟩)
else
match ofAscListAux₁ xs (s <<< 1) with
| (t, ⟨[], _⟩) => (t, ⟨[], Nat.zero_le _⟩)
| (l, ⟨y :: ys, h⟩) =>
have := Nat.le_succ_of_le h
let (r, ⟨zs, h'⟩) := ofAscListAux₁ ys (s <<< 1)
(link l y r, ⟨zs, le_trans h' (le_of_lt this)⟩)
termination_by l => l.length
#align ordnode.of_asc_list_aux₁ Ordnode.ofAscListAux₁
/-- Auxiliary definition for `ofAscList`. -/
def ofAscListAux₂ : List α → Ordnode α → ℕ → Ordnode α
| [] => fun t _ => t
| x :: xs => fun l s =>
match ofAscListAux₁ xs s with
| (r, ⟨ys, h⟩) =>
have := Nat.lt_succ_of_le h
ofAscListAux₂ ys (link l x r) (s <<< 1)
termination_by l => l.length
#align ordnode.of_asc_list_aux₂ Ordnode.ofAscListAux₂
/-- O(n). Build a set from a list which is already sorted. Performs no comparisons.
ofAscList [1, 2, 3] = {1, 2, 3}
ofAscList [3, 2, 1] = precondition violation -/
def ofAscList : List α → Ordnode α
| [] => nil
| x :: xs => ofAscListAux₂ xs (ι x) 1
#align ordnode.of_asc_list Ordnode.ofAscList
section
variable [LE α] [@DecidableRel α (· ≤ ·)]
/-- O(log n). Does the set (approximately) contain the element `x`? That is,
is there an element that is equivalent to `x` in the order?
1 ∈ {1, 2, 3} = true
4 ∈ {1, 2, 3} = false
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
(1, 1) ∈ {(0, 1), (1, 2)} = true
(3, 1) ∈ {(0, 1), (1, 2)} = false -/
def mem (x : α) : Ordnode α → Bool
| nil => false
| node _ l y r =>
match cmpLE x y with
| Ordering.lt => mem x l
| Ordering.eq => true
| Ordering.gt => mem x r
#align ordnode.mem Ordnode.mem
/-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order,
if it exists.
find 1 {1, 2, 3} = some 1
find 4 {1, 2, 3} = none
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
find (1, 1) {(0, 1), (1, 2)} = some (1, 2)
find (3, 1) {(0, 1), (1, 2)} = none -/
def find (x : α) : Ordnode α → Option α
| nil => none
| node _ l y r =>
match cmpLE x y with
| Ordering.lt => find x l
| Ordering.eq => some y
| Ordering.gt => find x r
#align ordnode.find Ordnode.find
instance : Membership α (Ordnode α) :=
⟨fun x t => t.mem x⟩
instance mem.decidable (x : α) (t : Ordnode α) : Decidable (x ∈ t) :=
Bool.decEq _ _
#align ordnode.mem.decidable Ordnode.mem.decidable
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, the function `f` is used to generate
the element to insert (being passed the current value in the set).
insertWith f 0 {1, 2, 3} = {0, 1, 2, 3}
insertWith f 1 {1, 2, 3} = {f 1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
insertWith f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)}
insertWith f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/
def insertWith (f : α → α) (x : α) : Ordnode α → Ordnode α
| nil => ι x
| node sz l y r =>
match cmpLE x y with
| Ordering.lt => balanceL (insertWith f x l) y r
| Ordering.eq => node sz l (f y) r
| Ordering.gt => balanceR l y (insertWith f x r)
#align ordnode.insert_with Ordnode.insertWith
/-- O(log n). Modify an element in the set with the given function,
doing nothing if the key is not found.
Note that the element returned by `f` must be equivalent to `x`.
adjustWith f 0 {1, 2, 3} = {1, 2, 3}
adjustWith f 1 {1, 2, 3} = {f 1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
adjustWith f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)}
adjustWith f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/
def adjustWith (f : α → α) (x : α) : Ordnode α → Ordnode α
| nil => nil
| _t@(node sz l y r) =>
match cmpLE x y with
| Ordering.lt => node sz (adjustWith f x l) y r
| Ordering.eq => node sz l (f y) r
| Ordering.gt => node sz l y (adjustWith f x r)
#align ordnode.adjust_with Ordnode.adjustWith
/-- O(log n). Modify an element in the set with the given function,
doing nothing if the key is not found.
Note that the element returned by `f` must be equivalent to `x`.
updateWith f 0 {1, 2, 3} = {1, 2, 3}
updateWith f 1 {1, 2, 3} = {2, 3} if f 1 = none
= {a, 2, 3} if f 1 = some a -/
def updateWith (f : α → Option α) (x : α) : Ordnode α → Ordnode α