@@ -3,3 +3,56 @@ fn len<T>(_input : [T]) -> comptime Field {}
3
3
4
4
#[builtin(arraysort)]
5
5
fn sort <T , N >(_a : [T ; N ]) -> [T ; N ] {}
6
+
7
+ // Sort with a custom sorting function.
8
+ fn sort_via <T , N >(mut a : [T ; N ], ordering : fn (T , T ) -> bool ) -> [T ; N ] {
9
+ for i in 1 ..len (a ) {
10
+ for j in 0 ..i {
11
+ if ordering (a [i ], a [j ]) {
12
+ let old_a_j = a [j ];
13
+ a [j ] = a [i ];
14
+ a [i ] = old_a_j ;
15
+ }
16
+ }
17
+ }
18
+ a
19
+ }
20
+
21
+ // Apply a function to each element of the array and an accumulator value,
22
+ // returning the final accumulated value. This function is also sometimes
23
+ // called `foldl`, `fold_left`, `reduce`, or `inject`.
24
+ fn fold <T , U , N >(array : [T ; N ], mut accumulator : U , f : fn (U , T ) -> U ) -> U {
25
+ for i in 0 .. len (array ) {
26
+ accumulator = f (accumulator , array [i ]);
27
+ }
28
+ accumulator
29
+ }
30
+
31
+ // Apply a function to each element of the array and an accumulator value,
32
+ // returning the final accumulated value. Unlike fold, reduce uses the first
33
+ // element of the given array as its starting accumulator value.
34
+ fn reduce <T , N >(array : [T ; N ], f : fn (T , T ) -> T ) -> T {
35
+ let mut accumulator = array [0 ];
36
+ for i in 1 .. len (array ) {
37
+ accumulator = f (accumulator , array [i ]);
38
+ }
39
+ accumulator
40
+ }
41
+
42
+ // Returns true if all elements in the array satisfy the predicate
43
+ fn all <T , N >(array : [T ; N ], predicate : fn (T ) -> bool ) -> bool {
44
+ let mut ret = true ;
45
+ for i in 0 .. len (array ) {
46
+ ret &= predicate (array [i ]);
47
+ }
48
+ ret
49
+ }
50
+
51
+ // Returns true if any element in the array satisfies the predicate
52
+ fn any <T , N >(array : [T ; N ], predicate : fn (T ) -> bool ) -> bool {
53
+ let mut ret = false ;
54
+ for i in 0 .. len (array ) {
55
+ ret |= predicate (array [i ]);
56
+ }
57
+ ret
58
+ }
0 commit comments