-
Notifications
You must be signed in to change notification settings - Fork 859
Expand file tree
/
Copy pathmap.fs
More file actions
1321 lines (1063 loc) · 42.6 KB
/
map.fs
File metadata and controls
1321 lines (1063 loc) · 42.6 KB
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) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
namespace Microsoft.FSharp.Collections
open System
open System.Collections.Generic
open System.Collections
open System.Diagnostics
open System.Runtime.CompilerServices
open System.Text
open Microsoft.FSharp.Core
open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators
[<NoEquality; NoComparison>]
[<AllowNullLiteral>]
type internal MapTree<'Key, 'Value>(k: 'Key, v: 'Value, h: int) =
member _.Height = h
member _.Key = k
member _.Value = v
new(k: 'Key, v: 'Value) = MapTree(k, v, 1)
[<NoEquality; NoComparison>]
[<Sealed>]
[<AllowNullLiteral>]
type internal MapTreeNode<'Key, 'Value>
(k: 'Key, v: 'Value, left: MapTree<'Key, 'Value>, right: MapTree<'Key, 'Value>, h: int) =
inherit MapTree<'Key, 'Value>(k, v, h)
member _.Left = left
member _.Right = right
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module MapTree =
let empty = null
let inline isEmpty (m: MapTree<'Key, 'Value>) =
isNull m
let inline private asNode (value: MapTree<'Key, 'Value>) : MapTreeNode<'Key, 'Value> =
value :?> MapTreeNode<'Key, 'Value>
let rec sizeAux acc (m: MapTree<'Key, 'Value>) =
if isEmpty m then
acc
else if m.Height = 1 then
acc + 1
else
let mn = asNode m
sizeAux (sizeAux (acc + 1) mn.Left) mn.Right
let size x =
sizeAux 0 x
#if TRACE_SETS_AND_MAPS
let mutable traceCount = 0
let mutable numOnes = 0
let mutable numNodes = 0
let mutable numAdds = 0
let mutable numRemoves = 0
let mutable numLookups = 0
let mutable numUnions = 0
let mutable totalSizeOnNodeCreation = 0.0
let mutable totalSizeOnMapAdd = 0.0
let mutable totalSizeOnMapLookup = 0.0
let mutable largestMapSize = 0
let mutable largestMapStackTrace = Unchecked.defaultof<_>
let report () =
traceCount <- traceCount + 1
if traceCount % 1000000 = 0 then
Console.WriteLine(
"#MapOne = {0}, #MapNode = {1}, #Add = {2}, #Remove = {3}, #Unions = {4}, #Lookups = {5}, avMapTreeSizeOnNodeCreation = {6}, avMapSizeOnCreation = {7}, avMapSizeOnLookup = {8}",
numOnes,
numNodes,
numAdds,
numRemoves,
numUnions,
numLookups,
(totalSizeOnNodeCreation / float (numNodes + numOnes)),
(totalSizeOnMapAdd / float numAdds),
(totalSizeOnMapLookup / float numLookups)
)
Console.WriteLine("#largestMapSize = {0}, largestMapStackTrace = {1}", largestMapSize, largestMapStackTrace)
let MapTree (k, v) =
report ()
numOnes <- numOnes + 1
totalSizeOnNodeCreation <- totalSizeOnNodeCreation + 1.0
MapTree(k, v)
let MapTreeNode (x, l, v, r, h) =
report ()
numNodes <- numNodes + 1
let n = MapTreeNode(x, l, v, r, h)
totalSizeOnNodeCreation <- totalSizeOnNodeCreation + float (size n)
n
#endif
let inline height (m: MapTree<'Key, 'Value>) =
if isEmpty m then 0 else m.Height
[<Literal>]
let tolerance = 2
let mk l k v r : MapTree<'Key, 'Value> =
let hl = height l
let hr = height r
let m = if hl < hr then hr else hl
if m = 0 then // m=0 ~ isEmpty l && isEmpty r
MapTree(k, v)
else
MapTreeNode(k, v, l, r, m + 1) :> MapTree<'Key, 'Value> // new map is higher by 1 than the highest
let rebalance t1 (k: 'Key) (v: 'Value) t2 : MapTree<'Key, 'Value> =
let t1h = height t1
let t2h = height t2
if t2h > t1h + tolerance then (* right is heavier than left *)
let t2' = asNode (t2)
(* one of the nodes must have height > height t1 + 1 *)
if height t2'.Left > t1h + 1 then (* balance left: combination *)
let t2l = asNode (t2'.Left)
mk (mk t1 k v t2l.Left) t2l.Key t2l.Value (mk t2l.Right t2'.Key t2'.Value t2'.Right)
else (* rotate left *)
mk (mk t1 k v t2'.Left) t2'.Key t2'.Value t2'.Right
else if t1h > t2h + tolerance then (* left is heavier than right *)
let t1' = asNode (t1)
(* one of the nodes must have height > height t2 + 1 *)
if height t1'.Right > t2h + 1 then
(* balance right: combination *)
let t1r = asNode (t1'.Right)
mk (mk t1'.Left t1'.Key t1'.Value t1r.Left) t1r.Key t1r.Value (mk t1r.Right k v t2)
else
mk t1'.Left t1'.Key t1'.Value (mk t1'.Right k v t2)
else
mk t1 k v t2
let rec add (comparer: IComparer<'Key>) k (v: 'Value) (m: MapTree<'Key, 'Value>) : MapTree<'Key, 'Value> =
if isEmpty m then
MapTree(k, v)
else
let c = comparer.Compare(k, m.Key)
if m.Height = 1 then
if c < 0 then
MapTreeNode(k, v, empty, m, 2) :> MapTree<'Key, 'Value>
elif c = 0 then
MapTree(k, v)
else
MapTreeNode(k, v, m, empty, 2) :> MapTree<'Key, 'Value>
else
let mn = asNode m
if c < 0 then
rebalance (add comparer k v mn.Left) mn.Key mn.Value mn.Right
elif c = 0 then
MapTreeNode(k, v, mn.Left, mn.Right, mn.Height) :> MapTree<'Key, 'Value>
else
rebalance mn.Left mn.Key mn.Value (add comparer k v mn.Right)
let rec tryGetValue (comparer: IComparer<'Key>) k (v: byref<'Value>) (m: MapTree<'Key, 'Value>) =
if isEmpty m then
false
else
let c = comparer.Compare(k, m.Key)
if c = 0 then
v <- m.Value
true
else if m.Height = 1 then
false
else
let mn = asNode m
tryGetValue comparer k &v (if c < 0 then mn.Left else mn.Right)
[<MethodImpl(MethodImplOptions.NoInlining)>]
let throwKeyNotFound () =
raise (KeyNotFoundException())
[<MethodImpl(MethodImplOptions.NoInlining)>]
let find (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) =
let mutable v = Unchecked.defaultof<'Value>
if tryGetValue comparer k &v m then
v
else
throwKeyNotFound ()
let tryFind (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) =
let mutable v = Unchecked.defaultof<'Value>
if tryGetValue comparer k &v m then
Some v
else
None
let partition1 (comparer: IComparer<'Key>) (f: OptimizedClosures.FSharpFunc<_, _, _>) k v (acc1, acc2) =
if f.Invoke(k, v) then
(add comparer k v acc1, acc2)
else
(acc1, add comparer k v acc2)
let rec partitionAux
(comparer: IComparer<'Key>)
(f: OptimizedClosures.FSharpFunc<_, _, _>)
(m: MapTree<'Key, 'Value>)
acc
=
if isEmpty m then
acc
else if m.Height = 1 then
partition1 comparer f m.Key m.Value acc
else
let mn = asNode m
let acc = partitionAux comparer f mn.Right acc
let acc = partition1 comparer f mn.Key mn.Value acc
partitionAux comparer f mn.Left acc
let partition (comparer: IComparer<'Key>) f m =
partitionAux comparer (OptimizedClosures.FSharpFunc<_, _, _>.Adapt f) m (empty, empty)
let filter1 (comparer: IComparer<'Key>) (f: OptimizedClosures.FSharpFunc<_, _, _>) k v acc =
if f.Invoke(k, v) then
add comparer k v acc
else
acc
let rec filterAux
(comparer: IComparer<'Key>)
(f: OptimizedClosures.FSharpFunc<_, _, _>)
(m: MapTree<'Key, 'Value>)
acc
=
if isEmpty m then
acc
else if m.Height = 1 then
filter1 comparer f m.Key m.Value acc
else
let mn = asNode m
let acc = filterAux comparer f mn.Left acc
let acc = filter1 comparer f mn.Key mn.Value acc
filterAux comparer f mn.Right acc
let filter (comparer: IComparer<'Key>) f m =
filterAux comparer (OptimizedClosures.FSharpFunc<_, _, _>.Adapt f) m empty
let rec spliceOutSuccessor (m: MapTree<'Key, 'Value>) =
if isEmpty m then
failwith "internal error: Map.spliceOutSuccessor"
else if m.Height = 1 then
m.Key, m.Value, empty
else
let mn = asNode m
if isEmpty mn.Left then
mn.Key, mn.Value, mn.Right
else
let k3, v3, l' = spliceOutSuccessor mn.Left in k3, v3, mk l' mn.Key mn.Value mn.Right
let rec remove (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) =
if isEmpty m then
empty
else
let c = comparer.Compare(k, m.Key)
if m.Height = 1 then
if c = 0 then empty else m
else
let mn = asNode m
if c < 0 then
rebalance (remove comparer k mn.Left) mn.Key mn.Value mn.Right
elif c = 0 then
if isEmpty mn.Left then
mn.Right
elif isEmpty mn.Right then
mn.Left
else
let sk, sv, r' = spliceOutSuccessor mn.Right
mk mn.Left sk sv r'
else
rebalance mn.Left mn.Key mn.Value (remove comparer k mn.Right)
let rec change
(comparer: IComparer<'Key>)
k
(u: 'Value option -> 'Value option)
(m: MapTree<'Key, 'Value>)
: MapTree<'Key, 'Value> =
if isEmpty m then
match u None with
| None -> m
| Some v -> MapTree(k, v)
else if m.Height = 1 then
let c = comparer.Compare(k, m.Key)
if c < 0 then
match u None with
| None -> m
| Some v -> MapTreeNode(k, v, empty, m, 2) :> MapTree<'Key, 'Value>
elif c = 0 then
match u (Some m.Value) with
| None -> empty
| Some v -> MapTree(k, v)
else
match u None with
| None -> m
| Some v -> MapTreeNode(k, v, m, empty, 2) :> MapTree<'Key, 'Value>
else
let mn = asNode m
let c = comparer.Compare(k, mn.Key)
if c < 0 then
rebalance (change comparer k u mn.Left) mn.Key mn.Value mn.Right
elif c = 0 then
match u (Some mn.Value) with
| None ->
if isEmpty mn.Left then
mn.Right
elif isEmpty mn.Right then
mn.Left
else
let sk, sv, r' = spliceOutSuccessor mn.Right
mk mn.Left sk sv r'
| Some v -> MapTreeNode(k, v, mn.Left, mn.Right, mn.Height) :> MapTree<'Key, 'Value>
else
rebalance mn.Left mn.Key mn.Value (change comparer k u mn.Right)
let rec mem (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) =
if isEmpty m then
false
else
let c = comparer.Compare(k, m.Key)
if m.Height = 1 then
c = 0
else
let mn = asNode m
if c < 0 then
mem comparer k mn.Left
else
(c = 0 || mem comparer k mn.Right)
let rec iterOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) (m: MapTree<'Key, 'Value>) =
if isEmpty m then
()
else if m.Height = 1 then
f.Invoke(m.Key, m.Value)
else
let mn = asNode m
iterOpt f mn.Left
f.Invoke(mn.Key, mn.Value)
iterOpt f mn.Right
let iter f m =
iterOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt f) m
let rec tryPickOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) (m: MapTree<'Key, 'Value>) =
if isEmpty m then
None
else if m.Height = 1 then
f.Invoke(m.Key, m.Value)
else
let mn = asNode m
match tryPickOpt f mn.Left with
| Some _ as res -> res
| None ->
match f.Invoke(mn.Key, mn.Value) with
| Some _ as res -> res
| None -> tryPickOpt f mn.Right
let tryPick f m =
tryPickOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt f) m
let rec existsOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) (m: MapTree<'Key, 'Value>) =
if isEmpty m then
false
else if m.Height = 1 then
f.Invoke(m.Key, m.Value)
else
let mn = asNode m
existsOpt f mn.Left || f.Invoke(mn.Key, mn.Value) || existsOpt f mn.Right
let exists f m =
existsOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt f) m
let rec forallOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) (m: MapTree<'Key, 'Value>) =
if isEmpty m then
true
else if m.Height = 1 then
f.Invoke(m.Key, m.Value)
else
let mn = asNode m
forallOpt f mn.Left && f.Invoke(mn.Key, mn.Value) && forallOpt f mn.Right
let forall f m =
forallOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt f) m
let rec map (f: 'Value -> 'Result) (m: MapTree<'Key, 'Value>) : MapTree<'Key, 'Result> =
if isEmpty m then
empty
else if m.Height = 1 then
MapTree(m.Key, f m.Value)
else
let mn = asNode m
let l2 = map f mn.Left
let v2 = f mn.Value
let r2 = map f mn.Right
MapTreeNode(mn.Key, v2, l2, r2, mn.Height) :> MapTree<'Key, 'Result>
let rec mapiOpt (f: OptimizedClosures.FSharpFunc<'Key, 'Value, 'Result>) (m: MapTree<'Key, 'Value>) =
if isEmpty m then
empty
else if m.Height = 1 then
MapTree(m.Key, f.Invoke(m.Key, m.Value))
else
let mn = asNode m
let l2 = mapiOpt f mn.Left
let v2 = f.Invoke(mn.Key, mn.Value)
let r2 = mapiOpt f mn.Right
MapTreeNode(mn.Key, v2, l2, r2, mn.Height) :> MapTree<'Key, 'Result>
let mapi f m =
mapiOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt f) m
let rec foldBackOpt (f: OptimizedClosures.FSharpFunc<_, _, _, _>) (m: MapTree<'Key, 'Value>) x =
if isEmpty m then
x
else if m.Height = 1 then
f.Invoke(m.Key, m.Value, x)
else
let mn = asNode m
let x = foldBackOpt f mn.Right x
let x = f.Invoke(mn.Key, mn.Value, x)
foldBackOpt f mn.Left x
let foldBack f m x =
foldBackOpt (OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt f) m x
let rec foldOpt (f: OptimizedClosures.FSharpFunc<_, _, _, _>) x (m: MapTree<'Key, 'Value>) =
if isEmpty m then
x
else if m.Height = 1 then
f.Invoke(x, m.Key, m.Value)
else
let mn = asNode m
let x = foldOpt f x mn.Left
let x = f.Invoke(x, mn.Key, mn.Value)
foldOpt f x mn.Right
let fold f x m =
foldOpt (OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt f) x m
let foldSectionOpt
(comparer: IComparer<'Key>)
lo
hi
(f: OptimizedClosures.FSharpFunc<_, _, _, _>)
(m: MapTree<'Key, 'Value>)
x
=
let rec foldFromTo (f: OptimizedClosures.FSharpFunc<_, _, _, _>) (m: MapTree<'Key, 'Value>) x =
if isEmpty m then
x
else if m.Height = 1 then
let cLoKey = comparer.Compare(lo, m.Key)
let cKeyHi = comparer.Compare(m.Key, hi)
let x =
if cLoKey <= 0 && cKeyHi <= 0 then
f.Invoke(m.Key, m.Value, x)
else
x
x
else
let mn = asNode m
let cLoKey = comparer.Compare(lo, mn.Key)
let cKeyHi = comparer.Compare(mn.Key, hi)
let x =
if cLoKey < 0 then
foldFromTo f mn.Left x
else
x
let x =
if cLoKey <= 0 && cKeyHi <= 0 then
f.Invoke(mn.Key, mn.Value, x)
else
x
let x =
if cKeyHi < 0 then
foldFromTo f mn.Right x
else
x
x
if comparer.Compare(lo, hi) = 1 then
x
else
foldFromTo f m x
let foldSection (comparer: IComparer<'Key>) lo hi f m x =
foldSectionOpt comparer lo hi (OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt f) m x
let toList (m: MapTree<'Key, 'Value>) =
let rec loop (m: MapTree<'Key, 'Value>) acc =
if isEmpty m then
acc
else if m.Height = 1 then
(m.Key, m.Value) :: acc
else
let mn = asNode m
loop mn.Left ((mn.Key, mn.Value) :: loop mn.Right acc)
loop m []
let toArray m =
m |> toList |> Array.ofList
let ofList comparer l =
List.fold (fun acc (k, v) -> add comparer k v acc) empty l
let rec mkFromEnumerator comparer acc (e: IEnumerator<_>) =
if e.MoveNext() then
let (x, y) = e.Current
mkFromEnumerator comparer (add comparer x y acc) e
else
acc
let ofArray comparer (arr: ('Key * 'Value) array) =
let mutable res = empty
for (x, y) in arr do
res <- add comparer x y res
res
let ofSeq comparer (c: seq<'Key * 'T>) =
match c with
| :? (('Key * 'T) array) as xs -> ofArray comparer xs
| :? (('Key * 'T) list) as xs -> ofList comparer xs
| _ ->
use ie = c.GetEnumerator()
mkFromEnumerator comparer empty ie
let copyToArray m (arr: _ array) i =
let mutable j = i
m
|> iter (fun x y ->
arr.[j] <- KeyValuePair(x, y)
j <- j + 1)
/// Imperative left-to-right iterators.
[<NoEquality; NoComparison>]
type MapIterator<'Key, 'Value when 'Key: comparison> =
{
/// invariant: always collapseLHS result
mutable stack: MapTree<'Key, 'Value> list
/// true when MoveNext has been called
mutable started: bool
}
// collapseLHS:
// a) Always returns either [] or a list starting with MapOne.
// b) The "fringe" of the set stack is unchanged.
let rec collapseLHS (stack: MapTree<'Key, 'Value> list) =
match stack with
| [] -> []
| m :: rest ->
if isEmpty m then
collapseLHS rest
else if m.Height = 1 then
stack
else
let mn = asNode m
collapseLHS (mn.Left :: MapTree(mn.Key, mn.Value) :: mn.Right :: rest)
let mkIterator m =
{
stack = collapseLHS [ m ]
started = false
}
let notStarted () =
raise (InvalidOperationException(SR.GetString(SR.enumerationNotStarted)))
let alreadyFinished () =
raise (InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished)))
let unexpectedStackForCurrent () =
failwith "Please report error: Map iterator, unexpected stack for current"
let unexpectedStackForMoveNext () =
failwith "Please report error: Map iterator, unexpected stack for moveNext"
let current i =
if i.started then
match i.stack with
| [] -> alreadyFinished ()
| m :: _ ->
if m.Height = 1 then
KeyValuePair<_, _>(m.Key, m.Value)
else
unexpectedStackForCurrent ()
else
notStarted ()
let rec moveNext i =
if i.started then
match i.stack with
| [] -> false
| m :: rest ->
if m.Height = 1 then
i.stack <- collapseLHS rest
not i.stack.IsEmpty
else
unexpectedStackForMoveNext ()
else
i.started <- true (* The first call to MoveNext "starts" the enumeration. *)
not i.stack.IsEmpty
let mkIEnumerator m =
let mutable i = mkIterator m
{ new IEnumerator<_> with
member _.Current = current i
interface System.Collections.IEnumerator with
member _.Current = box (current i)
member _.MoveNext() =
moveNext i
member _.Reset() =
i <- mkIterator m
interface System.IDisposable with
member _.Dispose() =
()
}
let rec leftmost m =
if isEmpty m then
throwKeyNotFound ()
else if m.Height = 1 then
(m.Key, m.Value)
else
let nd = asNode m
if isNull nd.Left then
(m.Key, m.Value)
else
leftmost nd.Left
let rec rightmost m =
if isEmpty m then
throwKeyNotFound ()
else if m.Height = 1 then
(m.Key, m.Value)
else
let nd = asNode m
if isNull nd.Right then
(m.Key, m.Value)
else
rightmost nd.Right
let rec binarySearch (comparer: IComparer<'Key>) k lower higher (m: MapTree<'Key, 'Value>) =
if isEmpty m then
lower, None, higher
else
let c = comparer.Compare(k, m.Key)
if m.Height = 1 then
if c = 0 then
lower, Some (m.Key, m.Value), higher
elif c < 0 then
lower, None, Some (m.Key, m.Value)
else
Some (m.Key, m.Value), None, higher
elif c = 0 then
let nd = asNode m
(if isEmpty nd.Left then None else Some (rightmost nd.Left)),
Some (m.Key, m.Value),
(if isEmpty nd.Right then None else Some (leftmost nd.Right))
elif c > 0 then
let nd = asNode m
binarySearch comparer k (Some (nd.Key, nd.Value)) higher nd.Right
else
let nd = asNode m
binarySearch comparer k lower (Some (nd.Key, nd.Value)) nd.Left
[<System.Diagnostics.DebuggerTypeProxy(typedefof<MapDebugView<_, _>>)>]
[<System.Diagnostics.DebuggerDisplay("Count = {Count}")>]
[<Sealed>]
[<CompiledName("FSharpMap`2")>]
type Map<[<EqualityConditionalOn>] 'Key, [<EqualityConditionalOn; ComparisonConditionalOn>] 'Value when 'Key: comparison>
(comparer: IComparer<'Key>, tree: MapTree<'Key, 'Value>) =
[<System.NonSerialized>]
// This type is logically immutable. This field is only mutated during deserialization.
let mutable comparer = comparer
[<System.NonSerialized>]
// This type is logically immutable. This field is only mutated during deserialization.
let mutable tree = tree
// This type is logically immutable. This field is only mutated during serialization and deserialization.
//
// WARNING: The compiled name of this field may never be changed because it is part of the logical
// WARNING: permanent serialization format for this type.
let mutable serializedData = null
// We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty
// set (it is just a lookup into a .NET table of type-instantiation-indexed static fields).
static let empty =
let comparer = LanguagePrimitives.FastGenericComparer<'Key>
new Map<'Key, 'Value>(comparer, MapTree.empty)
[<System.Runtime.Serialization.OnSerializingAttribute>]
member _.OnSerializing(context: System.Runtime.Serialization.StreamingContext) =
ignore context
serializedData <- MapTree.toArray tree |> Array.map (fun (k, v) -> KeyValuePair(k, v))
// Do not set this to null, since concurrent threads may also be serializing the data
//[<System.Runtime.Serialization.OnSerializedAttribute>]
//member _.OnSerialized(context: System.Runtime.Serialization.StreamingContext) =
// serializedData <- null
[<System.Runtime.Serialization.OnDeserializedAttribute>]
member _.OnDeserialized(context: System.Runtime.Serialization.StreamingContext) =
ignore context
comparer <- LanguagePrimitives.FastGenericComparer<'Key>
tree <-
serializedData
|> Array.map (fun kvp -> kvp.Key, kvp.Value)
|> MapTree.ofArray comparer
serializedData <- null
static member Empty: Map<'Key, 'Value> = empty
static member Create(ie: IEnumerable<_>) : Map<'Key, 'Value> =
let comparer = LanguagePrimitives.FastGenericComparer<'Key>
new Map<_, _>(comparer, MapTree.ofSeq comparer ie)
new(elements: seq<_>) =
let comparer = LanguagePrimitives.FastGenericComparer<'Key>
new Map<_, _>(comparer, MapTree.ofSeq comparer elements)
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member internal m.Comparer = comparer
//[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member internal m.Tree = tree
member m.Add(key, value) : Map<'Key, 'Value> =
#if TRACE_SETS_AND_MAPS
MapTree.report ()
MapTree.numAdds <- MapTree.numAdds + 1
let size = MapTree.size m.Tree + 1
MapTree.totalSizeOnMapAdd <- MapTree.totalSizeOnMapAdd + float size
if size > MapTree.largestMapSize then
MapTree.largestMapSize <- size
MapTree.largestMapStackTrace <- System.Diagnostics.StackTrace().ToString()
#endif
new Map<'Key, 'Value>(comparer, MapTree.add comparer key value tree)
member m.Change(key, f) : Map<'Key, 'Value> =
new Map<'Key, 'Value>(comparer, MapTree.change comparer key f tree)
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member m.IsEmpty = MapTree.isEmpty tree
member m.Item
with get (key: 'Key) =
#if TRACE_SETS_AND_MAPS
MapTree.report ()
MapTree.numLookups <- MapTree.numLookups + 1
MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree)
#endif
MapTree.find comparer key tree
member m.TryPick f =
MapTree.tryPick f tree
member m.Exists predicate =
MapTree.exists predicate tree
member m.Filter predicate =
new Map<'Key, 'Value>(comparer, MapTree.filter comparer predicate tree)
member m.ForAll predicate =
MapTree.forall predicate tree
member m.Fold f acc =
MapTree.foldBack f tree acc
member m.FoldSection (lo: 'Key) (hi: 'Key) f (acc: 'z) =
MapTree.foldSection comparer lo hi f tree acc
member m.Iterate f =
MapTree.iter f tree
member m.MapRange(f: 'Value -> 'Result) =
new Map<'Key, 'Result>(comparer, MapTree.map f tree)
member m.Map f =
new Map<'Key, 'b>(comparer, MapTree.mapi f tree)
member m.Partition predicate : Map<'Key, 'Value> * Map<'Key, 'Value> =
let r1, r2 = MapTree.partition comparer predicate tree
new Map<'Key, 'Value>(comparer, r1), new Map<'Key, 'Value>(comparer, r2)
member m.Count = MapTree.size tree
member m.ContainsKey key =
#if TRACE_SETS_AND_MAPS
MapTree.report ()
MapTree.numLookups <- MapTree.numLookups + 1
MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree)
#endif
MapTree.mem comparer key tree
member m.Remove key =
new Map<'Key, 'Value>(comparer, MapTree.remove comparer key tree)
member m.TryGetValue(key, [<System.Runtime.InteropServices.Out>] value: byref<'Value>) =
MapTree.tryGetValue comparer key &value tree
member m.TryFind key =
#if TRACE_SETS_AND_MAPS
MapTree.report ()
MapTree.numLookups <- MapTree.numLookups + 1
MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree)
#endif
MapTree.tryFind comparer key tree
member m.ToList() =
MapTree.toList tree
member m.ToArray() =
MapTree.toArray tree
member m.Keys = KeyCollection(m) :> ICollection<'Key>
member m.Values = ValueCollection(m) :> ICollection<'Value>
member m.MinKeyValue = MapTree.leftmost tree
member m.MaxKeyValue = MapTree.rightmost tree
member m.BinarySearch key =
MapTree.binarySearch comparer key None None tree
static member ofList l : Map<'Key, 'Value> =
let comparer = LanguagePrimitives.FastGenericComparer<'Key>
new Map<_, _>(comparer, MapTree.ofList comparer l)
member this.ComputeHashCode() =
let combineHash x y =
(x <<< 1) + y + 631
let mutable res = 0
for (KeyValue(x, y)) in this do
res <- combineHash res (hash x)
res <- combineHash res (Unchecked.hash y)
res
override this.Equals that =
match that with
| :? Map<'Key, 'Value> as that ->
use e1 = (this :> seq<_>).GetEnumerator()
use e2 = (that :> seq<_>).GetEnumerator()
let rec loop () =
let m1 = e1.MoveNext()
let m2 = e2.MoveNext()
(m1 = m2)
&& (not m1
|| (let e1c = e1.Current
let e2c = e2.Current
((e1c.Key = e2c.Key) && (Unchecked.equals e1c.Value e2c.Value) && loop ())))
loop ()
| _ -> false
override this.GetHashCode() =
this.ComputeHashCode()
interface IStructuralEquatable with
member this.Equals(that, comparer) =
match that with
| :? Map<'Key, 'Value> as that ->
use e1 = (this :> seq<_>).GetEnumerator()
use e2 = (that :> seq<_>).GetEnumerator()
let rec loop () =
let m1 = e1.MoveNext()
let m2 = e2.MoveNext()
(m1 = m2)
&& (not m1
|| (let e1c = e1.Current
let e2c = e2.Current
(comparer.Equals(e1c.Key, e2c.Key)
&& comparer.Equals(e1c.Value, e2c.Value)
&& loop ())))
loop ()
| _ -> false
member this.GetHashCode(comparer) =
let combineHash x y =
(x <<< 1) + y + 631
let mutable res = 0
for (KeyValue(x, y)) in this do
res <- combineHash res (comparer.GetHashCode x)
res <- combineHash res (comparer.GetHashCode y)
res
interface IEnumerable<KeyValuePair<'Key, 'Value>> with
member _.GetEnumerator() =
MapTree.mkIEnumerator tree
interface IEnumerable with
member _.GetEnumerator() =
(MapTree.mkIEnumerator tree :> IEnumerator)
interface IDictionary<'Key, 'Value> with
member m.Item
with get x = m.[x]
and set _ _ = raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))
member m.Keys = m.Keys
member m.Values = m.Values
member m.Add(_, _) =
raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))
member m.ContainsKey k =
m.ContainsKey k
member m.TryGetValue(k, r) =
m.TryGetValue(k, &r)
member m.Remove(_) =
raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))
interface ICollection<KeyValuePair<'Key, 'Value>> with
member _.Add(_) =
raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))
member _.Clear() =
raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))
member _.Remove(_) =
raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))
member m.Contains x =
m.ContainsKey x.Key && Unchecked.equals m.[x.Key] x.Value
member _.CopyTo(arr, i) =
MapTree.copyToArray tree arr i
member _.IsReadOnly = true
member m.Count = m.Count
interface System.IComparable with
member m.CompareTo(obj: objnull) =
match obj with
| :? Map<'Key, 'Value> as m2 ->
Seq.compareWith
(fun (kvp1: KeyValuePair<_, _>) (kvp2: KeyValuePair<_, _>) ->
let c = comparer.Compare(kvp1.Key, kvp2.Key) in
if c <> 0 then
c
else
Unchecked.compare kvp1.Value kvp2.Value)
m
m2