This repository has been archived by the owner on May 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FSharp.Core.Shim.fs
2148 lines (1928 loc) · 110 KB
/
FSharp.Core.Shim.fs
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
namespace Microsoft.FSharp.Core.CompilerServices
open System.Threading.Tasks
open System.Threading.Tasks
module RuntimeHelpers =
open System.Collections.Generic
[<Struct; NoComparison; NoEquality>]
type internal StructBox<'T when 'T : equality>(value:'T) =
member x.Value = value
static member Comparer =
let gcomparer = HashIdentity.Structural<'T>
{ new IEqualityComparer<StructBox<'T>> with
member __.GetHashCode(v) = gcomparer.GetHashCode(v.Value)
member __.Equals(v1,v2) = gcomparer.Equals(v1.Value,v2.Value) }
namespace Microsoft.FSharp.Core
[<assembly: AutoOpen("Microsoft.FSharp.Core")>]
do()
module internal SR =
let keyNotFoundAlt = "An index satisfying the predicate was not found in the collection."
let arrayWasEmpty = "The input array was empty."
let inputSequenceEmpty = "The input sequence was empty."
let inputMustBeNonNegative = "The input must be non-negative."
let notEnoughElements = "The input sequence has an insufficient number of elements."
let inputSequenceTooLong = "The input sequence contains more than one element."
let arraysHadDifferentLengths = "The arrays have different lengths."
let outOfRange = "The index is outside the legal range."
let inputListWasEmpty = "The input list was empty."
let indexOutOfBounds = "The index was outside the range of elements in the list."
let resetNotSupported = "Reset is not supported on this enumerator."
let enumerationNotStarted = "Enumeration has not started. Call MoveNext."
let enumerationAlreadyFinished = "Enumeration already finished."
let GetString(name:System.String) : System.String = name
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
[<RequireQualifiedAccess>]
module String =
let inline private emptyIfNull str =
if str = null then "" else str
/// <summary>Returns a new string containing only the characters of the string
/// for which the given predicate returns "true"</summary>
/// <param name="predicate">The function to test the input characters.</param>
/// <param name="list">The input string.</param>
/// <returns>A string containing only the characters that satisfy the predicate.</returns>
[<CompiledName("Filter")>]
let filter (predicate:char -> bool) (str:string) =
let str = emptyIfNull str
let res = System.Text.StringBuilder(str.Length)
for i = 0 to str.Length - 1 do
let ch = str.[i]
if predicate ch then
res.Append(ch) |> ignore
res.ToString()
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Option =
/// <summary><c>filter f inp</c> evaluates to <c>match inp with None -> None | Some x -> if f x then Some x else None</c>.</summary>
/// <param name="predicate">A function that evaluates whether the value contained in the option should remain, or be filtered out.</param>
/// <param name="option">The input option.</param>
/// <returns>The input if the predicate evaluates to true; otherwise, None.</returns>
[<CompiledName("Filter")>]
let filter f inp = match inp with None -> None | Some x -> if f x then Some x else None
/// <summary>Convert the option to a Nullable value.</summary>
/// <param name="option">The input option.</param>
/// <returns>The result value.</returns>
[<CompiledName("ToNullable")>]
let toNullable option = match option with None -> System.Nullable() | Some v -> System.Nullable(v)
/// <summary>Convert a Nullable value to an option.</summary>
/// <param name="value">The input nullable value.</param>
/// <returns>The result option.</returns>
[<CompiledName("OfNullable")>]
let ofNullable (value:System.Nullable<'T>) = if value.HasValue then Some value.Value else None
/// <summary>Convert a potentially null value to an option.</summary>
/// <param name="value">The input value.</param>
/// <returns>The result option.</returns>
[<CompiledName("OfObj")>]
let ofObj value = match value with null -> None | _ -> Some value
/// <summary>Convert an option to a potentially null value.</summary>
/// <param name="value">The input value.</param>
/// <returns>The result value, which is null if the input was None.</returns>
[<CompiledName("ToObj")>]
let toObj value = match value with None -> null | Some x -> x
[<AutoOpen>]
module Operators =
/// <summary>Try to unbox a strongly typed value.</summary>
/// <param name="value">The boxed value.</param>
/// <returns>The unboxed result as an option.</returns>
[<CompiledName("TryUnbox")>]
let inline tryUnbox (x:obj) =
match x with
| :? 'T as v -> Some v
| _ -> None
/// <summary>Determines whether the given value is null.</summary>
/// <param name="value">The value to check.</param>
/// <returns>True when value is null, false otherwise.</returns>
[<CompiledName("IsNull")>]
let inline isNull (value : 'T) =
match value with
| null -> true
| _ -> false
namespace Local.LanguagePrimitives
module ErrorStrings =
open Microsoft.FSharp.Core
let InputArrayEmptyString = SR.GetString(SR.arrayWasEmpty)
let InputSequenceEmptyString = SR.GetString(SR.inputSequenceEmpty)
let InputMustBeNonNegativeString = SR.GetString(SR.inputMustBeNonNegative)
namespace Microsoft.FSharp.Primitives.Basics
module internal Array =
open Microsoft.FSharp.Core
open System.Collections.Generic
// The input parameter should be checked by callers if necessary
let inline zeroCreateUnchecked (count:int) =
Array.zeroCreate count
let inline fastComparerForArraySort<'t when 't : comparison> () =
Comparer.Default
let inline indexNotFound() = raise (new System.Collections.Generic.KeyNotFoundException(SR.GetString(SR.keyNotFoundAlt)))
let findBack f (array: _[]) =
let rec loop i =
if i < 0 then indexNotFound()
elif f array.[i] then array.[i]
else loop (i - 1)
loop (array.Length - 1)
let tryFindBack f (array: _[]) =
let rec loop i =
if i < 0 then None
elif f array.[i] then Some array.[i]
else loop (i - 1)
loop (array.Length - 1)
let findIndexBack f (array: _[]) =
let rec loop i =
if i < 0 then indexNotFound()
elif f array.[i] then i
else loop (i - 1)
loop (array.Length - 1)
let tryFindIndexBack f (array: _[]) =
let rec loop i =
if i < 0 then None
elif f array.[i] then Some i
else loop (i - 1)
loop (array.Length - 1)
let mapFold f acc (array : _[]) =
match array.Length with
| 0 -> [| |], acc
| len ->
let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)
let mutable acc = acc
let res = zeroCreateUnchecked len
for i = 0 to len - 1 do
let h',s' = f.Invoke(acc,array.[i])
res.[i] <- h'
acc <- s'
res, acc
let mapFoldBack f (array : _[]) acc =
match array.Length with
| 0 -> [| |], acc
| len ->
let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)
let mutable acc = acc
let res = zeroCreateUnchecked len
for i = len - 1 downto 0 do
let h',s' = f.Invoke(array.[i],acc)
res.[i] <- h'
acc <- s'
res, acc
let scanSubRight f (array : _[]) start fin initState =
let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)
let mutable state = initState
let res = zeroCreateUnchecked (fin-start+2)
res.[fin - start + 1] <- state
for i = fin downto start do
state <- f.Invoke(array.[i], state);
res.[i - start] <- state
res
let stableSortWithKeysAndComparer (cFast:IComparer<'Key>) (c:IComparer<'Key>) (array:array<'T>) (keys:array<'Key>) =
// 'places' is an array or integers storing the permutation performed by the sort
let places = zeroCreateUnchecked array.Length
for i = 0 to array.Length - 1 do
places.[i] <- i
System.Array.Sort<_,_>(keys, places, cFast)
// 'array2' is a copy of the original values
let array2 = (array.Clone() :?> array<'T>)
// Walk through any chunks where the keys are equal
let mutable i = 0
let len = array.Length
let intCompare = fastComparerForArraySort<int>()
while i < len do
let mutable j = i
let ki = keys.[i]
while j < len && (j = i || c.Compare(ki, keys.[j]) = 0) do
j <- j + 1
// Copy the values into the result array and re-sort the chunk if needed by the original place indexes
for n = i to j - 1 do
array.[n] <- array2.[places.[n]]
if j - i >= 2 then
System.Array.Sort<_,_>(places, array, i, j-i, intCompare)
i <- j
let stableSortInPlaceWith (comparer:'T -> 'T -> int) (array : array<'T>) =
let len = array.Length
if len > 1 then
let keys = (array.Clone() :?> array<'T>)
let comparer = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(comparer)
let c = { new IComparer<'T> with member __.Compare(x,y) = comparer.Invoke(x,y) }
stableSortWithKeysAndComparer c c array keys
module internal List =
open System.Collections.Generic
open Local.LanguagePrimitives.ErrorStrings
open Microsoft.FSharp.Core
let private arrayZeroCreate = Array.zeroCreate
let rec distinctToFreshConsTail (cons: LinkedList<_>) (hashSet:HashSet<_>) (list:'T list) =
match list with
| [] -> ()
| (x::rest) ->
if hashSet.Add(x) then
cons.AddLast(x) |> ignore
distinctToFreshConsTail cons hashSet rest
else
distinctToFreshConsTail cons hashSet rest
let distinctWithComparer (comparer: System.Collections.Generic.IEqualityComparer<'T>) (list:'T list) =
match list with
| [] -> []
| [h] -> [h]
| (x::rest) ->
let hashSet = System.Collections.Generic.HashSet<'T>(comparer)
hashSet.Add(x) |> ignore
let cons = LinkedList<'T>()
cons.AddLast(x) |> ignore
distinctToFreshConsTail cons hashSet rest
cons |> Seq.toList
let rec distinctByToFreshConsTail (cons: LinkedList<_>) (hashSet:HashSet<_>) keyf (list:'T list) =
match list with
| [] -> ()
| (x::rest) ->
if hashSet.Add(keyf x) then
cons.AddLast(x) |> ignore
distinctByToFreshConsTail cons hashSet keyf rest
else
distinctByToFreshConsTail cons hashSet keyf rest
let distinctByWithComparer (comparer: System.Collections.Generic.IEqualityComparer<'Key>) (keyf:'T -> 'Key) (list:'T list) =
match list with
| [] -> []
| [h] -> [h]
| (x::rest) ->
let hashSet = System.Collections.Generic.HashSet<'Key>(comparer)
hashSet.Add(keyf x) |> ignore
let cons = LinkedList<'T>()
cons.AddLast(x) |> ignore
distinctByToFreshConsTail cons hashSet keyf rest
cons |> Seq.toList
let rec mapFoldToFreshConsTail (cons: LinkedList<'U>) (f:OptimizedClosures.FSharpFunc<'State, 'T, 'U * 'State>) acc xs =
match xs with
| [] -> acc
| (h::t) ->
let x',s' = f.Invoke(acc,h)
cons.AddLast(x') |> ignore
mapFoldToFreshConsTail cons f s' t
let mapFold f acc xs =
match xs with
| [] -> [], acc
| [h] ->
let x',s' = f acc h
[x'],s'
| (h::t) ->
let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)
let (x': 'c),s' = f.Invoke(acc,h)
let cons = LinkedList<_>()
cons.AddLast(x') |> ignore
let s' = mapFoldToFreshConsTail cons f s' t
(cons |> Seq.toList), s'
let rec takeFreshConsTail (cons: LinkedList<_>) n (l:'T list) =
if n = 0 then () else
match l with
| [] -> raise <| System.InvalidOperationException (SR.GetString(SR.notEnoughElements))
| x::xs ->
cons.AddLast(x) |> ignore
takeFreshConsTail cons (n - 1) xs
let take n (l:'T list) =
if n < 0 then invalidArg "count" InputMustBeNonNegativeString
if n = 0 then [] else
match l with
| [] -> raise <| System.InvalidOperationException (SR.GetString(SR.notEnoughElements))
| x::xs ->
let cons = LinkedList<_>()
cons.AddLast(x) |> ignore
takeFreshConsTail cons (n - 1) xs
cons |> Seq.toList
let rec takeWhileFreshConsTail (cons: LinkedList<_>) p (l:'T list) =
match l with
| [] -> ()
| x::xs ->
if not (p x) then () else
cons.AddLast(x) |> ignore
takeWhileFreshConsTail cons p xs
let takeWhile p (l: 'T list) =
match l with
| [] -> l
| x :: ([] as nil) -> if p x then l else nil
| x::xs ->
if not (p x) then [] else
let cons = LinkedList<_>()
cons.AddLast(x) |> ignore
takeWhileFreshConsTail cons p xs
cons |> Seq.toList
let rec splitAtFreshConsTail (cons: LinkedList<_>) index (l:'T list) =
if index = 0 then
l
else
match l with
| [] -> raise <| System.InvalidOperationException (SR.GetString(SR.notEnoughElements))
| x :: xs ->
cons.AddLast(x) |> ignore
splitAtFreshConsTail cons (index - 1) xs
let splitAt index (l:'T list) =
if index < 0 then invalidArg "index" (SR.GetString(SR.inputMustBeNonNegative))
if index = 0 then [], l else
match l with
| [] -> raise <| System.InvalidOperationException (SR.GetString(SR.notEnoughElements))
| [_] -> if index = 1 then l, [] else raise <| System.InvalidOperationException (SR.GetString(SR.notEnoughElements))
| x::xs ->
if index = 1 then [x], xs else
let cons = LinkedList<_>()
cons.AddLast(x) |> ignore
let tail = splitAtFreshConsTail cons (index - 1) xs
cons |> Seq.toList, tail
let rec filterToFreshConsTail (cons: LinkedList<_>) f (l:'T list) =
match l with
| [] -> ()
| h::t ->
if f h then
cons.AddLast(h) |> ignore
filterToFreshConsTail cons f t
else
filterToFreshConsTail cons f t
let rec filter f (l:'T list) =
match l with
| [] -> l
| h :: ([] as nil) -> if f h then l else nil
| h::t ->
if f h then
let cons = LinkedList<_>()
cons.AddLast(h) |> ignore
filterToFreshConsTail cons f t;
cons |> Seq.toList
else
filter f t
let rec indexedToFreshConsTail (cons: LinkedList<_>) (xs:'T list) i =
match xs with
| [] -> ()
| (h::t) ->
cons.AddLast((i, h)) |> ignore
indexedToFreshConsTail cons t (i+1)
let indexed (xs:'T list) =
match xs with
| [] -> []
| [h] -> [(0,h)]
| (h::t) ->
let cons = LinkedList<_>()
cons.AddLast((0,h)) |> ignore
indexedToFreshConsTail cons t 1
cons |> Seq.toList
let rec truncateToFreshConsTail (cons: LinkedList<_>) count (list:'T list) =
if count = 0 then () else
match list with
| [] -> ()
| h::t ->
cons.AddLast(h) |> ignore
truncateToFreshConsTail cons (count-1) t
let truncate count (list:'T list) =
if count < 0 then invalidArg "count" (SR.GetString(SR.inputMustBeNonNegative))
match list with
| [] -> list
| _ :: ([] as nil) -> if count > 0 then list else nil
| h::t ->
if count = 0 then []
else
let cons = LinkedList<_>()
cons.AddLast(h) |> ignore
truncateToFreshConsTail cons (count-1) t
cons |> Seq.toList
let rec unfoldToFreshConsTail (cons: LinkedList<_>) (f:'State -> ('T * 'State) option) s =
match f s with
| None -> ()
| Some (x,s') ->
cons.AddLast(x) |> ignore
unfoldToFreshConsTail cons f s'
let unfold (f:'State -> ('T * 'State) option) (s:'State) =
match f s with
| None -> []
| Some (x,s') ->
let cons = LinkedList<_>()
cons.AddLast(x) |> ignore
unfoldToFreshConsTail cons f s'
cons |> Seq.toList
let rec windowedToFreshConsTail (cons: LinkedList<_>) windowSize i (l:'T list) (arr:'T[]) =
match l with
| [] -> ()
| h::t ->
arr.[i] <- h
let i = (i+1) % windowSize
let result = arrayZeroCreate windowSize : 'T[]
System.Array.Copy(arr, i, result, 0, windowSize - i)
System.Array.Copy(arr, 0, result, windowSize - i, i)
cons.AddLast(result) |> ignore
windowedToFreshConsTail cons windowSize i t arr
let windowed windowSize (list:'T list) =
if windowSize <= 0 then invalidArg "windowSize" (SR.GetString(SR.inputMustBeNonNegative))
match list with
| [] -> []
| _ ->
let arr = arrayZeroCreate windowSize
let rec loop i r l =
match l with
| [] -> if r = 0 && i = windowSize then [arr.Clone() :?> 'T[]] else []
| h::t ->
arr.[i] <- h
if r = 0 then
let cons = LinkedList<_>()
cons.AddLast(arr.Clone() :?> 'T[]) |> ignore
windowedToFreshConsTail cons windowSize 0 t arr
cons |> Seq.toList
else
loop (i+1) (r-1) t
loop 0 (windowSize - 1) list
namespace Microsoft.FSharp.Collections
[<assembly: AutoOpen("Microsoft.FSharp.Collections")>]
do()
module IEnumerator =
open System.Collections
open System.Collections.Generic
open Microsoft.FSharp.Core
let noReset() = raise (new System.NotSupportedException(SR.GetString(SR.resetNotSupported)))
let notStarted() = raise (new System.InvalidOperationException(SR.GetString(SR.enumerationNotStarted)))
let alreadyFinished() = raise (new System.InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished)))
[<NoEquality; NoComparison>]
type MapEnumeratorState =
| NotStarted
| InProcess
| Finished
[<AbstractClass>]
type MapEnumerator<'T> () =
let mutable state = NotStarted
[<DefaultValue(false)>]
val mutable private curr : 'T
member this.GetCurrent () =
match state with
| NotStarted -> notStarted()
| Finished -> alreadyFinished()
| InProcess -> ()
this.curr
abstract DoMoveNext : byref<'T> -> bool
abstract Dispose : unit -> unit
interface IEnumerator<'T> with
member this.Current = this.GetCurrent()
interface IEnumerator with
member this.Current = box(this.GetCurrent())
member this.MoveNext () =
state <- InProcess
if this.DoMoveNext(&this.curr) then
true
else
state <- Finished
false
member this.Reset() = noReset()
interface System.IDisposable with
member this.Dispose() = this.Dispose()
let rec tryItem index (e : IEnumerator<'T>) =
if not (e.MoveNext()) then None
elif index = 0 then Some(e.Current)
else tryItem (index-1) e
let rec nth index (e : IEnumerator<'T>) =
if not (e.MoveNext()) then invalidArg "index" (SR.GetString(SR.notEnoughElements))
if index = 0 then e.Current
else nth (index-1) e
let mapi2 f (e1 : IEnumerator<_>) (e2 : IEnumerator<_>) : IEnumerator<_> =
let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)
let i = ref (-1)
upcast
{ new MapEnumerator<_>() with
member this.DoMoveNext curr =
i := !i + 1
if (e1.MoveNext() && e2.MoveNext()) then
curr <- f.Invoke(!i, e1.Current, e2.Current)
true
else
false
member this.Dispose() =
try
e1.Dispose()
finally
e2.Dispose()
}
let map3 f (e1 : IEnumerator<_>) (e2 : IEnumerator<_>) (e3 : IEnumerator<_>) : IEnumerator<_> =
let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)
upcast
{ new MapEnumerator<_>() with
member this.DoMoveNext curr =
let n1 = e1.MoveNext()
let n2 = e2.MoveNext()
let n3 = e3.MoveNext()
if n1 && n2 && n3 then
curr <- f.Invoke(e1.Current, e2.Current, e3.Current)
true
else
false
member this.Dispose() =
try
e1.Dispose()
finally
try
e2.Dispose()
finally
e3.Dispose()
}
[<RequireQualifiedAccess>]
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Array =
open System
open System.Collections.Generic
open Microsoft.FSharp.Core
open Local
open Local.LanguagePrimitives.ErrorStrings
open Microsoft.FSharp.Core.CompilerServices
let private empty = Array.empty
let private init = Array.init
let private filter = Array.filter
let sortWith = Array.sortWith
let inline private checkNonNull argName arg =
match box arg with
| null -> nullArg argName
| _ -> ()
/// <summary>Returns the last element for which the given function returns 'true'.
/// Raise <c>KeyNotFoundException</c> if no such element exists.</summary>
/// <param name="predicate">The function to test the input elements.</param>
/// <param name="array">The input array.</param>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">Thrown if <c>predicate</c>
/// never returns true.</exception>
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <returns>The last element for which <c>predicate</c> returns true.</returns>
[<CompiledName("FindBack")>]
let findBack f (array: _[]) =
checkNonNull "array" array
Microsoft.FSharp.Primitives.Basics.Array.findBack f array
/// <summary>Returns the last element for which the given function returns <c>true</c>.
/// Return <c>None</c> if no such element exists.</summary>
/// <param name="predicate">The function to test the input elements.</param>
/// <param name="array">The input array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <returns>The last element that satisfies the predicate, or None.</returns>
[<CompiledName("TryFindBack")>]
let tryFindBack f (array: _[]) =
checkNonNull "array" array
Microsoft.FSharp.Primitives.Basics.Array.tryFindBack f array
/// <summary>Returns an array that contains no duplicate entries according to generic hash and
/// equality comparisons on the entries.
/// If an element occurs multiple times in the array then the later occurrences are discarded.</summary>
///
/// <param name="array">The input array.</param>
///
/// <returns>The result array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
[<CompiledName("Distinct")>]
let distinct (array:'T[]) =
checkNonNull "array" array
let temp = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length
let mutable i = 0
let hashSet = HashSet<'T>(HashIdentity.Structural<'T>)
for v in array do
if hashSet.Add(v) then
temp.[i] <- v
i <- i + 1
let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked i : 'T[]
Array.Copy(temp, 0, res, 0, i)
res
/// <summary>Returns an array that contains no duplicate entries according to the
/// generic hash and equality comparisons on the keys returned by the given key-generating function.
/// If an element occurs multiple times in the array then the later occurrences are discarded.</summary>
///
/// <param name="projection">A function transforming the array items into comparable keys.</param>
/// <param name="array">The input array.</param>
///
/// <returns>The result array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
[<CompiledName("DistinctBy")>]
let distinctBy keyf (array:'T[]) =
checkNonNull "array" array
let temp = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length
let mutable i = 0
let hashSet = HashSet<_>(HashIdentity.Structural<_>)
for v in array do
if hashSet.Add(keyf v) then
temp.[i] <- v
i <- i + 1
let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked i : 'T[]
Array.Copy(temp, 0, res, 0, i)
res
/// <summary>Returns the first N elements of the array.</summary>
/// <remarks>Throws <c>InvalidOperationException</c>
/// if the count exceeds the number of elements in the array. <c>Array.truncate</c>
/// returns as many items as the array contains instead of throwing an exception.</remarks>
///
/// <param name="count">The number of items to take.</param>
/// <param name="array">The input array.</param>
///
/// <returns>The result array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <exception cref="System.ArgumentException">Thrown when the input array is empty.</exception>
/// <exception cref="System.InvalidOperationException">Thrown when count exceeds the number of elements
/// in the list.</exception>
[<CompiledName("Take")>]
let take count (array : 'T[]) =
checkNonNull "array" array
if count < 0 then invalidArg "count" (SR.GetString(SR.inputMustBeNonNegative))
if count = 0 then empty else
if count > array.Length then
raise <| System.InvalidOperationException (SR.GetString(SR.notEnoughElements))
let res : 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count
Array.Copy(array, 0, res, 0, count)
res
/// <summary>Returns an array that contains all elements of the original array while the
/// given predicate returns <c>true</c>, and then returns no further elements.</summary>
///
/// <param name="predicate">A function that evaluates to false when no more items should be returned.</param>
/// <param name="array">The input array.</param>
///
/// <returns>The result array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
[<CompiledName("TakeWhile")>]
let takeWhile predicate (array: 'T[]) =
checkNonNull "array" array
if array.Length = 0 then empty else
let mutable count = 0
while count < array.Length && predicate array.[count] do
count <- count + 1
let res : 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count
Array.Copy(array, 0, res, 0, count)
res
/// <summary>Splits an array into two arrays, at the given index.</summary>
/// <param name="index">The index at which the array is split.</param>
/// <param name="array">The input array.</param>
/// <returns>The two split arrays.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <exception cref="System.InvalidOperationException">Thrown when split index exceeds the number of elements
/// in the array.</exception>
[<CompiledName("SplitAt")>]
let splitAt index (array:'T[]) =
checkNonNull "array" array
if index < 0 then invalidArg "index" (SR.GetString(SR.inputMustBeNonNegative))
if array.Length < index then raise <| System.InvalidOperationException (SR.GetString(SR.notEnoughElements))
if index = 0 then
let right : 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length
Array.Copy(array, right, array.Length)
[||],right
elif index = array.Length then
let left : 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length
Array.Copy(array, left, array.Length)
left,[||] else
let res1 : 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked index
let res2 : 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (array.Length-index)
Array.Copy(array, 0, res1, 0, index)
Array.Copy(array, index, res2, 0, array.Length-index)
res1,res2
/// <summary>Creates an array by replicating the given initial value.</summary>
/// <param name="count">The number of elements to replicate.</param>
/// <param name="initial">The value to replicate</param>
/// <returns>The generated array.</returns>
[<CompiledName("Replicate")>]
let replicate count x =
if count < 0 then invalidArg "count" (SR.GetString(SR.inputMustBeNonNegative))
let arr = (Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count : 'T array)
for i = 0 to count - 1 do
arr.[i] <- x
arr
/// <summary>Compares two arrays using the given comparison function, element by element.
/// Returns the first non-zero result from the comparison function. If the end of an array
/// is reached it returns a -1 if the first array is shorter and a 1 if the second array
/// is shorter.</summary>
///
/// <param name="comparer">A function that takes an element from each array and returns an int.
/// If it evaluates to a non-zero value iteration is stopped and that value is returned.</param>
/// <param name="array1">The first input array.</param>
/// <param name="array2">The second input array.</param>
///
/// <returns>The first non-zero value from the comparison function.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when either of the input arrays
/// is null.</exception>
[<CompiledName("CompareWith")>]
let inline compareWith (comparer:'T -> 'T -> int) (array1: 'T[]) (array2: 'T[]) =
checkNonNull "array1" array1
checkNonNull "array2" array2
let length1 = array1.Length
let length2 = array2.Length
let minLength = Operators.min length1 length2
let rec loop index =
if index = minLength then
if length1 = length2 then 0
elif length1 < length2 then -1
else 1
else
let result = comparer array1.[index] array2.[index]
if result <> 0 then result else
loop (index+1)
loop 0
/// <summary>Applies a key-generating function to each element of an array and returns an array yielding unique
/// keys and their number of occurrences in the original array.</summary>
///
/// <param name="projection">A function transforming each item of the input array into a key to be
/// compared against the others.</param>
/// <param name="array">The input array.</param>
///
/// <returns>The result array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
[<CompiledName("CountBy")>]
let countBy projection (array:'T[]) =
checkNonNull "array" array
let dict = new Dictionary<Microsoft.FSharp.Core.CompilerServices.RuntimeHelpers.StructBox<'Key>,int>(Microsoft.FSharp.Core.CompilerServices.RuntimeHelpers.StructBox<'Key>.Comparer)
// Build the groupings
for v in array do
let key = Microsoft.FSharp.Core.CompilerServices.RuntimeHelpers.StructBox (projection v)
let mutable prev = Unchecked.defaultof<_>
if dict.TryGetValue(key, &prev) then dict.[key] <- prev + 1 else dict.[key] <- 1
let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked dict.Count
let mutable i = 0
for group in dict do
res.[i] <- group.Key.Value, group.Value
i <- i + 1
res
/// <summary>Returns the first element of the array, or
/// <c>None</c> if the array is empty.</summary>
/// <param name="array">The input array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <returns>The first element of the array or None.</returns>
[<CompiledName("TryHead")>]
let tryHead (array : 'T[]) =
checkNonNull "array" array
if array.Length = 0 then None
else Some array.[0]
/// <summary>Returns a new array containing only the elements of the array
/// for which the given predicate returns "true".</summary>
/// <param name="predicate">The function to test the input elements.</param>
/// <param name="array">The input array.</param>
/// <returns>An array containing the elements for which the given predicate returns true.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
[<CompiledName("Where")>]
let where f (array: _[]) = filter f array
/// <summary>Returns the index of the last element in the array
/// that satisfies the given predicate. Raise <c>KeyNotFoundException</c> if
/// none of the elements satisfy the predicate.</summary>
/// <param name="predicate">The function to test the input elements.</param>
/// <param name="array">The input array.</param>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">Thrown if <c>predicate</c>
/// never returns true.</exception>
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <returns>The index of the last element in the array that satisfies the given predicate.</returns>
[<CompiledName("FindIndexBack")>]
let findIndexBack f (array : _[]) =
checkNonNull "array" array
Microsoft.FSharp.Primitives.Basics.Array.findIndexBack f array
/// <summary>Returns the last element of the array.</summary>
/// <param name="array">The input array.</param>
/// <returns>The last element of the array.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <exception cref="System.ArgumentException">Thrown when the input does not have any elements.</exception>
[<CompiledName("Last")>]
let inline last (array : 'T[]) =
checkNonNull "array" array
if array.Length = 0 then invalidArg "array" InputArrayEmptyString
array.[array.Length-1]
/// <summary>Returns the last element of the array.
/// Return <c>None</c> if no such element exists.</summary>
/// <param name="array">The input array.</param>
/// <returns>The last element of the array or None.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when the input sequence is null.</exception>
[<CompiledName("TryLast")>]
let tryLast (array : 'T[]) =
checkNonNull "array" array
if array.Length = 0 then None
else Some array.[array.Length-1]
/// <summary>Returns the only element of the array.</summary>
///
/// <param name="array">The input array.</param>
///
/// <returns>The only element of the array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <exception cref="System.ArgumentException">Thrown when the input does not have precisely one element.</exception>
[<CompiledName("ExactlyOne")>]
let exactlyOne (array:'T[]) =
checkNonNull "array" array
if array.Length = 1 then array.[0]
elif array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString
else invalidArg "array" (SR.GetString(SR.inputSequenceTooLong))
/// <summary>Applies a key-generating function to each element of an array and yields an array of
/// unique keys. Each unique key contains an array of all elements that match
/// to this key.</summary>
///
/// <param name="projection">A function that transforms an element of the array into a comparable key.</param>
/// <param name="array">The input array.</param>
///
/// <returns>The result array.</returns>
[<CompiledName("GroupBy")>]
let groupBy keyf (array: 'T[]) =
checkNonNull "array" array
let dict = new Dictionary<RuntimeHelpers.StructBox<'Key>,ResizeArray<'T>>(RuntimeHelpers.StructBox<'Key>.Comparer)
// Build the groupings
for i = 0 to (array.Length - 1) do
let v = array.[i]
let key = RuntimeHelpers.StructBox (keyf v)
let ok, prev = dict.TryGetValue(key)
if ok then
prev.Add(v)
else
let prev = new ResizeArray<'T>(1)
dict.[key] <- prev
prev.Add(v)
// Return the array-of-arrays.
let result = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked dict.Count
let mutable i = 0
for group in dict do
result.[i] <- group.Key.Value, group.Value.ToArray()
i <- i + 1
result
/// <summary>Returns the first element of the array.</summary>
///
/// <param name="array">The input array.</param>
///
/// <returns>The first element of the array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
/// <exception cref="System.ArgumentException">Thrown when the input array is empty.</exception>
[<CompiledName("Head")>]
let head (array : 'T[]) =
checkNonNull "array" array
if array.Length = 0 then invalidArg "array" InputArrayEmptyString else array.[0]
/// <summary>Returns an array of each element in the input array and its predecessor, with the
/// exception of the first element which is only returned as the predecessor of the second element.</summary>
///
/// <param name="array">The input array.</param>
///
/// <returns>The result array.</returns>
///
/// <exception cref="System.ArgumentNullException">Thrown when the input sequence is null.</exception>
[<CompiledName("Pairwise")>]
let pairwise (array: 'T[]) =
checkNonNull "array" array
if array.Length < 2 then [||] else
init (array.Length-1) (fun i -> array.[i],array.[i+1])
/// <summary>Returns an array that contains one item only.</summary>
///
/// <param name="value">The input item.</param>
///
/// <returns>The result array of one item.</returns>
[<CompiledName("Singleton")>]
let inline singleton value = [|value|]
/// <summary>Tests if the array contains the specified element.</summary>
/// <param name="value">The value to locate in the input array.</param>
/// <param name="array">The input array.</param>
/// <returns>True if the input array contains the specified element; false otherwise.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
[<CompiledName("Contains")>]
let inline contains e (array:'T[]) =
checkNonNull "array" array
let mutable state = false
let mutable i = 0
while (not state && i < array.Length) do
state <- e = array.[i]
i <- i + 1
state
/// <summary>Builds a new array whose elements are the corresponding elements of the input array
/// paired with the integer index (from 0) of each element.</summary>
/// <param name="array">The input array.</param>
/// <returns>The array of indexed elements.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when the input array is null.</exception>
[<CompiledName("Indexed")>]
let indexed (array: 'T[]) =
checkNonNull "array" array
let len = array.Length