-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy patharray.mbt
1765 lines (1701 loc) · 43.9 KB
/
array.mbt
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 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// Creates a new dynamic array from a fixed-size array.
///
/// Parameters:
///
/// * `arr` : The fixed-size array to convert. The elements of this array will be
/// copied to the new array.
///
/// Returns a new dynamic array containing all elements from the input fixed-size
/// array.
///
/// Example:
///
/// ```moonbit
/// test "Array::from_fixed_array" {
/// let fixed = FixedArray::make(3, 42)
/// let dynamic = Array::from_fixed_array(fixed)
/// inspect!(dynamic, content="[42, 42, 42]")
/// }
/// ```
pub fn Array::from_fixed_array[T](arr : FixedArray[T]) -> Array[T] {
let len = arr.length()
let arr2 = Array::make_uninit(len)
UninitializedArray::unsafe_blit_fixed(arr2.buffer(), 0, arr, 0, len)
arr2
}
///|
/// Creates a new array with a specified length and initializes all elements with
/// the given value.
///
/// Parameters:
///
/// * `length` : The length of the array to create. Must be a non-negative
/// integer.
/// * `initial_value` : The value used to initialize all elements in the array.
///
/// Returns a new array of type `Array[T]` with `length` elements, where each
/// element is initialized to `initial_value`.
///
/// Throws an error if `length` is negative.
///
/// Example:
///
/// ```moonbit
/// test "Array::make" {
/// let arr = Array::make(3, 42)
/// inspect!(arr, content="[42, 42, 42]")
/// }
///
/// test "panic Array::make/negative_length" {
/// ignore(Array::make(-1, 0))
/// }
/// ```
pub fn Array::make[T](len : Int, elem : T) -> Array[T] {
let arr = Array::make_uninit(len)
for i in 0..<len {
arr.unsafe_set(i, elem)
}
arr
}
///|
/// Returns the total capacity of the array, which is the number of elements that
/// the array can hold without requiring reallocation of its internal buffer.
///
/// Parameters:
///
/// * `array` : The array whose capacity is to be determined.
///
/// Returns the current capacity of the array as an integer.
///
/// Example:
///
/// ```moonbit
/// test "Array::capacity" {
/// let arr = Array::new(capacity=10)
/// arr.push(1)
/// arr.push(2)
/// inspect!(arr.capacity(), content="10")
/// }
/// ```
pub fn Array::capacity[T](self : Array[T]) -> Int {
self.buffer()._.length()
}
///|
/// Retrieves the element at the specified index from an array without bounds
/// checking.
///
/// Parameters:
///
/// * `array` : The array from which to retrieve the element.
/// * `index` : The position in the array from which to retrieve the element.
///
/// Returns the element at the specified index.
///
/// Example:
///
/// ```moonbit
/// test "Array::unsafe_get/basic" {
/// let arr = [1, 2, 3]
/// inspect!(arr.unsafe_get(1), content="2")
/// }
/// ```
///
/// @intrinsic %array.unsafe_get
pub fn Array::unsafe_get[T](self : Array[T], idx : Int) -> T {
self.buffer()[idx]
}
///|
/// Retrieves an element from the array at the specified index.
///
/// Parameters:
///
/// * `array` : The array to get the element from.
/// * `index` : The position in the array from which to retrieve the element.
///
/// Returns the element at the specified index.
///
/// Throws a panic if the index is negative or greater than or equal to the
/// length of the array.
///
/// Example:
///
/// ```moonbit
/// test "Array::op_get" {
/// let arr = [1, 2, 3]
/// inspect!(arr[1], content="2")
/// }
///
/// test "panic Array::op_get/out_of_bounds" {
/// let arr = [1, 2, 3]
/// ignore(arr[3]) // Index out of bounds
/// }
/// ```
///
/// @alert unsafe "Panic if index is out of bounds"
/// @intrinsic %array.get
pub fn Array::op_get[T](self : Array[T], index : Int) -> T {
let len = self.length()
guard index >= 0 && index < len
self.buffer()[index]
}
///|
/// Retrieves the element at the specified index from the array.
///
/// Parameters:
///
/// * `self` : The array to get the element from.
/// * `index` : The position in the array from which to retrieve the element.
///
/// Returns `Some(element)` if the index is within bounds, or `None` if the index
/// is out of bounds.
///
/// Example:
///
/// ```moonbit
/// test "Array::get" {
/// let arr = [1, 2, 3]
/// inspect!(arr.get(-1), content="None")
/// inspect!(arr.get(0), content="Some(1)")
/// inspect!(arr.get(3), content="None")
/// }
/// ```
pub fn Array::get[T](self : Array[T], index : Int) -> T? {
let len = self.length()
guard index >= 0 && index < len else { None }
Some(self.unsafe_get(index))
}
///|
/// @intrinsic %array.unsafe_set
fn Array::unsafe_set[T](self : Array[T], idx : Int, val : T) -> Unit {
self.buffer()[idx] = val
}
///|
/// Sets the element at the specified index in the array to a new value. The
/// original value at that index is overwritten.
///
/// Parameters:
///
/// * `array` : The array to modify.
/// * `index` : The position in the array where the value will be set.
/// * `value` : The new value to assign at the specified index.
///
/// Throws an error if `index` is negative or greater than or equal to the length
/// of the array.
///
/// Example:
///
/// ```moonbit
/// test "Array::op_set" {
/// let arr = [1, 2, 3]
/// arr[1] = 42
/// inspect!(arr, content="[1, 42, 3]")
/// }
///
/// test "panic Array::op_set/out_of_bounds" {
/// let arr = [1, 2, 3]
/// arr[3] = 42 // Index out of bounds
/// }
/// ```
///
/// @alert unsafe "Panic if index is out of bounds."
/// @intrinsic %array.set
pub fn Array::op_set[T](self : Array[T], index : Int, value : T) -> Unit {
let len = self.length()
guard index >= 0 && index < len
self.buffer()[index] = value
}
///|
/// Compares two arrays for equality. Returns true if both arrays have the same
/// length and contain equal elements in the same order.
///
/// Parameters:
///
/// * `self` : The first array to compare.
/// * `other` : The second array to compare.
///
/// Returns true if the arrays are equal, false otherwise.
///
/// Example:
///
/// ```moonbit
/// test "Array::op_equal" {
/// let arr1 = [1, 2, 3]
/// let arr2 = [1, 2, 3]
/// let arr3 = [1, 2, 4]
/// inspect!(arr1 == arr2, content="true")
/// inspect!(arr1 == arr3, content="false")
/// }
/// ```
pub fn Array::op_equal[T : Eq](self : Array[T], other : Array[T]) -> Bool {
let self_len = self.length()
let other_len = other.length()
guard self_len == other_len else { return false }
for i in 0..<self_len {
guard self.unsafe_get(i) == other.unsafe_get(i) else { break false }
} else {
true
}
}
///|
/// Compares two arrays lexicographically.
///
/// First compares the lengths of the arrays. If they differ, returns -1 if the
/// first array is shorter, 1 if it's longer. If the lengths are equal, compares
/// elements pairwise until a difference is found or all elements have been
/// compared.
///
/// Parameters:
///
/// * `self` : The first array to compare.
/// * `other` : The second array to compare.
///
/// Returns an integer that indicates the relative order:
///
/// * A negative value if `self` is less than `other`
/// * Zero if `self` equals `other`
/// * A positive value if `self` is greater than `other`
///
/// Example:
///
/// ```moonbit
/// test "Array::compare" {
/// let arr1 = [1, 2, 3]
/// let arr2 = [1, 2, 4]
/// let arr3 = [1, 2]
/// inspect!(arr1.compare(arr2), content="-1") // arr1 < arr2
/// inspect!(arr2.compare(arr1), content="1") // arr2 > arr1
/// inspect!(arr1.compare(arr3), content="1") // arr1 > arr3 (longer)
/// inspect!(arr1.compare(arr1), content="0") // arr1 = arr1
/// }
/// ```
pub fn Array::compare[T : Compare](self : Array[T], other : Array[T]) -> Int {
let len_self = self.length()
let len_other = other.length()
guard let 0 = len_self.compare(len_other) else { x => return x }
for i in 0..<len_self {
let cmp = self.unsafe_get(i).compare(other.unsafe_get(i))
guard let 0 = cmp else { x => break x }
} else {
0
}
}
///|
/// Concatenates two arrays into a new array. The resulting array contains all
/// elements from the first array followed by all elements from the second array.
///
/// Parameters:
///
/// * `self` : The first array to concatenate.
/// * `other` : The second array to concatenate.
///
/// Returns a new array containing all elements from both arrays in order.
///
/// Example:
///
/// ```moonbit
/// test "Array::op_add" {
/// let a = [1, 2, 3]
/// let b = [4, 5]
/// inspect!(a + b, content="[1, 2, 3, 4, 5]")
/// }
/// ```
pub fn Array::op_add[T](self : Array[T], other : Array[T]) -> Array[T] {
let result = Array::make_uninit(self.length() + other.length())
UninitializedArray::unsafe_blit(
result.buffer(),
0,
self.buffer(),
0,
self.length(),
)
UninitializedArray::unsafe_blit(
result.buffer(),
self.length(),
other.buffer(),
0,
other.length(),
)
result
}
///|
/// Appends all elements from one array to the end of another array. The elements
/// are added in-place, modifying the original array.
///
/// Parameters:
///
/// * `self` : The array to append to.
/// * `other` : The array whose elements will be appended.
///
/// Example:
///
/// ```moonbit
/// test "Array::append" {
/// let v1 = [1, 2, 3]
/// let v2 = [4, 5, 6]
/// v1.append(v2)
/// inspect!(v1, content="[1, 2, 3, 4, 5, 6]")
/// }
///
/// test "Array::append/empty" {
/// let v1 = [1, 2, 3]
/// let v2 : Array[Int] = []
/// v1.append(v2)
/// inspect!(v1, content="[1, 2, 3]")
/// }
/// ```
pub fn Array::append[T](self : Array[T], other : Array[T]) -> Unit {
other.blit_to(
self,
len=other.length(),
src_offset=0,
dst_offset=self.length(),
)
}
///|
/// Iterates through each element of the array in order, applying the given
/// function to each element.
///
/// Parameters:
///
/// * `array` : The array to iterate over.
/// * `function` : A function that takes a single element of type `T` as input
/// and returns `Unit`. This function is applied to each element of the array in
/// order.
///
/// Example:
///
/// ```moonbit
/// test "Array::each" {
/// let arr = [1, 2, 3]
/// let mut sum = 0
/// arr.each(fn(x) { sum = sum + x })
/// inspect!(sum, content="6")
/// }
/// ```
pub fn Array::each[T](self : Array[T], f : (T) -> Unit) -> Unit {
for v in self {
f(v)
}
}
///|
/// Iterates over the elements of the array in reverse order, applying the given
/// function to each element.
///
/// Parameters:
///
/// * `array` : The array to iterate over.
/// * `f` : A function that takes an element of type `T` and returns `Unit`. This
/// function is applied to each element of the array in reverse order.
///
/// Example:
///
/// ```
/// let v = [3, 4, 5]
/// let mut sum = 0
/// v.rev_each(fn(x) { sum = sum - x })
/// @json.inspect!(sum, content=-12)
/// ```
pub fn Array::rev_each[T](self : Array[T], f : (T) -> Unit) -> Unit {
let len = self.length()
for i in 0..<len {
f(self[len - i - 1])
}
}
///|
/// Iterates over the elements of the array with index in reversed order.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// let mut sum = 0
/// v.rev_eachi(fn(i, x) { sum = sum + x + i })
/// assert_eq!(sum, 15)
/// ```
pub fn Array::rev_eachi[T](self : Array[T], f : (Int, T) -> Unit) -> Unit {
let len = self.length()
for i in 0..<len {
f(i, self[len - i - 1])
}
}
///|
/// Iterates over the elements of the array with index.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// let mut sum = 0
/// v.eachi(fn (i, x) {sum = sum + x + i})
/// ```
pub fn Array::eachi[T](self : Array[T], f : (Int, T) -> Unit) -> Unit {
for i, v in self {
f(i, v)
}
}
///|
/// Clears the array, removing all values.
///
/// This method has no effect on the allocated capacity of the array, only setting the length to 0.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// v.clear()
/// assert_eq!(v.length(), 0)
/// ```
pub fn Array::clear[T](self : Array[T]) -> Unit {
self.unsafe_truncate_to_length(0)
}
///|
/// Maps a function over the elements of the array.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// let v2 = v.map(fn (x) {x + 1})
/// assert_eq!(v2, [4, 5, 6])
/// ```
pub fn Array::map[T, U](self : Array[T], f : (T) -> U) -> Array[U] {
let arr = Array::make_uninit(self.length())
for i, v in self {
arr.unsafe_set(i, f(v))
}
arr
}
///|
/// Maps a function over the elements of the array in place.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// v.map_inplace(fn (x) {x + 1})
/// assert_eq!(v, [4, 5, 6])
/// ```
pub fn Array::map_inplace[T](self : Array[T], f : (T) -> T) -> Unit {
for i, v in self {
self[i] = f(v)
}
}
///|
/// Maps a function over the elements of the array with index.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// let v2 = v.mapi(fn (i, x) {x + i})
/// assert_eq!(v2, [3, 5, 7])
/// ```
pub fn Array::mapi[T, U](self : Array[T], f : (Int, T) -> U) -> Array[U] {
if self.length() == 0 {
return []
}
let arr = Array::make_uninit(self.length())
for i, v in self {
arr.unsafe_set(i, f(i, v))
}
arr
}
///|
/// Maps a function over the elements of the array with index in place.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// v.mapi_inplace(fn (i, x) {x + i})
/// assert_eq!(v, [3, 5, 7])
/// ```
pub fn Array::mapi_inplace[T](self : Array[T], f : (Int, T) -> T) -> Unit {
for i, v in self {
self[i] = f(i, v)
}
}
///|
/// Creates a new array containing all elements from the input array that satisfy
/// the given predicate function.
///
/// Parameters:
///
/// * `array` : The array to filter.
/// * `predicate` : A function that takes an element and returns a boolean
/// indicating whether the element should be included in the result.
///
/// Returns a new array containing only the elements for which the predicate
/// function returns `true`. The relative order of the elements is preserved.
///
/// Example:
///
/// ```moonbit
/// test "Array::filter" {
/// let arr = [1, 2, 3, 4, 5]
/// let evens = arr.filter(fn(x) { x % 2 == 0 })
/// inspect!(evens, content="[2, 4]")
/// }
/// ```
pub fn Array::filter[T](self : Array[T], f : (T) -> Bool) -> Array[T] {
let arr = []
for v in self {
if f(v) {
arr.push(v)
}
}
arr
}
///|
/// Tests whether the array contains no elements.
///
/// Parameters:
///
/// * `array` : The array to check.
///
/// Returns `true` if the array has no elements, `false` otherwise.
///
/// Example:
///
/// ```moonbit
/// test "Array::is_empty" {
/// let empty : Array[Int] = []
/// inspect!(empty.is_empty(), content="true")
/// let non_empty = [1, 2, 3]
/// inspect!(non_empty.is_empty(), content="false")
/// }
/// ```
pub fn Array::is_empty[T](self : Array[T]) -> Bool {
self.length() == 0
}
///|
/// Tests whether the array is sorted in ascending order.
///
/// Parameters:
///
/// * `self` : The array to be tested.
/// * `T` : The type of elements in the array. Must implement the `Compare`
/// trait.
///
/// Returns a boolean value indicating whether the array is sorted in ascending
/// order:
///
/// * `true` if the array is empty, contains only one element, or all elements
/// are in ascending order.
/// * `false` if any element is greater than the element that follows it.
///
/// Example:
///
/// ```moonbit
/// test "Array::is_sorted/basic" {
/// let ascending = [1, 2, 3, 4, 5]
/// let descending = [5, 4, 3, 2, 1]
/// let unsorted = [1, 3, 2, 4, 5]
/// inspect!(ascending.is_sorted(), content="true")
/// inspect!(descending.is_sorted(), content="false")
/// inspect!(unsorted.is_sorted(), content="false")
/// }
/// ```
pub fn Array::is_sorted[T : Compare](self : Array[T]) -> Bool {
for i = 1 {
if i >= self.length() {
break true
}
if self[i - 1] > self[i] {
break false
}
continue i + 1
}
}
///|
/// Reverses the order of elements in an array in place, modifying the original
/// array.
///
/// Parameters:
///
/// * `self` : The array to be reversed.
///
/// Example:
///
/// ```moonbit
/// test "Array::rev_inplace" {
/// let arr = [1, 2, 3, 4, 5]
/// arr.rev_inplace()
/// inspect!(arr, content="[5, 4, 3, 2, 1]")
/// }
///
/// test "Array::rev_inplace/empty" {
/// let arr : Array[Int] = []
/// arr.rev_inplace()
/// inspect!(arr, content="[]")
/// }
/// ```
pub fn Array::rev_inplace[T](self : Array[T]) -> Unit {
for i = 0; i < self.length() / 2; i = i + 1 {
let temp = self.unsafe_get(i)
self.unsafe_set(i, self.unsafe_get(self.length() - i - 1))
self.unsafe_set(self.length() - i - 1, temp)
}
}
///|
/// Creates a new array with elements in reversed order.
///
/// Parameters:
///
/// * `self` : The array to be reversed.
///
/// Returns a new array containing the same elements as the input array but in
/// reverse order. The original array remains unchanged.
///
/// Example:
///
/// ```moonbit
/// test "Array::rev" {
/// let arr = [1, 2, 3, 4, 5]
/// inspect!(arr.rev(), content="[5, 4, 3, 2, 1]")
/// inspect!(arr, content="[1, 2, 3, 4, 5]") // original array unchanged
/// }
/// ```
pub fn Array::rev[T](self : Array[T]) -> Array[T] {
let arr = Array::make_uninit(self.length())
for i = 0; i < self.length(); i = i + 1 {
arr.unsafe_set(i, self.unsafe_get(self.length() - i - 1))
}
arr
}
///|
/// Split the array into two at the given index.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// let (v1, v2) = v.split_at(1)
/// assert_eq!(v1, [3])
/// assert_eq!(v2, [4, 5])
/// ```
/// TODO: perf could be optimized
/// @alert unsafe "Panic if index is out of bounds."
pub fn Array::split_at[T](self : Array[T], index : Int) -> (Array[T], Array[T]) {
if index < 0 || index > self.length() {
let len = self.length()
abort(
"index out of bounds: the len is from 0 to \{len} but the index is \{index}",
)
}
let v1 = Array::make_uninit(index)
let v2 = Array::make_uninit(self.length() - index)
UninitializedArray::unsafe_blit(v1.buffer(), 0, self.buffer(), 0, index)
if index != self.length() {
UninitializedArray::unsafe_blit(
v2.buffer(),
0,
self.buffer(),
index,
self.length() - index,
)
}
(v1, v2)
}
///|
/// Checks whether the array contains an element equal to the given value.
///
/// Parameters:
///
/// * `array` : The array to search in.
/// * `value` : The value to search for.
///
/// Returns `true` if the array contains an element equal to the given value,
/// `false` otherwise.
///
/// Example:
///
/// ```moonbit
/// test "Array::contains" {
/// let arr = [1, 2, 3, 4, 5]
/// inspect!(arr.contains(3), content="true")
/// inspect!(arr.contains(6), content="false")
/// }
///
/// test "Array::contains/empty" {
/// let arr : Array[Int] = []
/// inspect!(arr.contains(1), content="false")
/// }
/// ```
pub fn Array::contains[T : Eq](self : Array[T], value : T) -> Bool {
for v in self {
if v == value {
break true
}
} else {
false
}
}
///|
/// Checks if the array begins with all elements of the provided prefix array in
/// order.
///
/// Parameters:
///
/// * `self` : The array to check against.
/// * `prefix` : The array containing the sequence of elements to look for at the
/// beginning.
///
/// Returns `true` if the array starts with all elements in `prefix` in the same
/// order, `false` otherwise. An empty prefix array always returns `true`, and a
/// prefix longer than the array always returns `false`.
///
/// Example:
///
/// ```moonbit
/// test "Array::starts_with" {
/// let arr = [1, 2, 3, 4, 5]
/// inspect!(arr.starts_with([1, 2]), content="true")
/// inspect!(arr.starts_with([2, 3]), content="false")
/// inspect!(arr.starts_with([]), content="true")
/// inspect!(arr.starts_with([1, 2, 3, 4, 5, 6]), content="false")
/// }
/// ```
pub fn Array::starts_with[T : Eq](self : Array[T], prefix : Array[T]) -> Bool {
if prefix.length() > self.length() {
return false
}
for i = 0; i < prefix.length(); i = i + 1 {
if self.unsafe_get(i) != prefix.unsafe_get(i) {
break false
}
} else {
true
}
}
///|
/// Tests if an array ends with the given suffix.
///
/// Parameters:
///
/// * `self` : The array to check.
/// * `suffix` : The array to test against.
///
/// Returns `true` if the array ends with the given suffix, `false` otherwise.
///
/// Example:
///
/// ```moonbit
/// test "Array::ends_with/basic" {
/// let arr = [1, 2, 3, 4, 5]
/// inspect!(arr.ends_with([4, 5]), content="true")
/// inspect!(arr.ends_with([3, 4]), content="false")
/// inspect!(arr.ends_with([]), content="true")
/// }
///
/// test "Array::ends_with/empty" {
/// let arr : Array[Int] = []
/// inspect!(arr.ends_with([]), content="true")
/// inspect!(arr.ends_with([1]), content="false")
/// }
/// ```
pub fn Array::ends_with[T : Eq](self : Array[T], suffix : Array[T]) -> Bool {
if suffix.length() > self.length() {
return false
}
for i = 0; i < suffix.length(); i = i + 1 {
if self.unsafe_get(self.length() - suffix.length() + i) !=
suffix.unsafe_get(i) {
break false
}
} else {
true
}
}
///|
/// Removes a prefix from an array if it exists.
///
/// Parameters:
///
/// * `array` : The array to remove the prefix from.
/// * `prefix` : The array to be removed from the beginning of `array`.
///
/// Returns `Some(array)` containing the remaining elements after removing the
/// prefix if the array starts with the prefix, or `None` if the array doesn't
/// start with the prefix.
///
/// Example:
///
/// ```moonbit
/// test "strip_prefix" {
/// let arr = [1, 2, 3, 4, 5]
/// inspect!(arr.strip_prefix([1, 2]), content="Some([3, 4, 5])")
/// inspect!(arr.strip_prefix([2, 3]), content="None")
/// }
/// ```
pub fn Array::strip_prefix[T : Eq](
self : Array[T],
prefix : Array[T]
) -> Array[T]? {
if self.starts_with(prefix) {
let v = Array::make_uninit(self.length() - prefix.length())
UninitializedArray::unsafe_blit(
v.buffer(),
0,
self.buffer(),
prefix.length(),
self.length() - prefix.length(),
)
Some(v)
} else {
None
}
}
///|
/// Strip a suffix from the array.
///
/// If the array ends with the suffix, return the array before the suffix, otherwise return None.
///
/// # Example
/// ```
/// let v = [3, 4, 5]
/// let v2 = v.strip_suffix([5])
/// assert_eq!(v2, Some([3, 4]))
/// ```
pub fn Array::strip_suffix[T : Eq](
self : Array[T],
suffix : Array[T]
) -> Array[T]? {
if self.ends_with(suffix) {
let v = Array::make_uninit(self.length() - suffix.length())
let len = self.length() - suffix.length()
UninitializedArray::unsafe_blit(v.buffer(), 0, self.buffer(), 0, len)
Some(v)
} else {
None
}
}
///|
/// Searches for the first occurrence of a value in the array and returns its
/// index.
///
/// Parameters:
///
/// * `self` : The array to search in.
/// * `value` : The value to search for.
///
/// Returns an `Option` containing the index of the first occurrence of `value`
/// if found, or `None` if the value is not present in the array.
///
/// Example:
///
/// ```moonbit
/// test "Array::search" {
/// let arr = [1, 2, 3, 2, 4]
/// inspect!(arr.search(2), content="Some(1)") // first occurrence
/// inspect!(arr.search(5), content="None") // not found
/// }
/// ```
pub fn Array::search[T : Eq](self : Array[T], value : T) -> Int? {
for i, v in self {
if v == value {
break Some(i)
}
} else {
None
}
}
///|
/// Searches the array for the first element that satisfies the predicate
/// function.
///
/// Parameters:
///
/// * `array` : The array to search in.
/// * `predicate` : A function that takes an element and returns a boolean
/// indicating whether the element satisfies the search condition.
///
/// Returns the index of the first element that satisfies the predicate, or
/// `None` if no such element is found.
///
/// Example:
///
/// ```moonbit
/// test "find_index" {
/// let arr = [1, 2, 3, 4, 5]
/// inspect!(arr.search_by(fn(x) { x > 3 }), content="Some(3)")
/// inspect!(arr.search_by(fn(x) { x > 10 }), content="None")
/// }
/// ```
///
/// @alert deprecated "Use `search_by` instead."
/// @coverage.skip
pub fn Array::find_index[T](self : Array[T], f : (T) -> Bool) -> Int? {
self.search_by(f)
}
///|
/// Search the index of the first element that satisfies the predicate.
///
/// # Example
///
/// ```
/// let v = [1, 2, 3, 4, 5]
/// match v.search_by(fn(x) { x == 3 }) {
/// Some(index) => assert_eq!(index, 2) // 2
/// None => println("Not found")
/// }
/// ```
pub fn Array::search_by[T](self : Array[T], f : (T) -> Bool) -> Int? {
for i, v in self {
if f(v) {
break Some(i)
}
} else {
None
}
}
///|
/// Performs a binary search on a sorted array to find the index of a given element.
///
/// # Example
/// ```