Skip to content

Commit d186c39

Browse files
authored
arrays: fix arrays.fold, when the init value in the call, is an array (#21921)
1 parent b5ba466 commit d186c39

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

vlib/arrays/arrays.v

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,12 @@ pub fn filter_indexed[T](array []T, predicate fn (idx int, elem T) bool) []T {
331331
// assert r == 5
332332
// ```
333333
pub fn fold[T, R](array []T, init R, fold_op fn (acc R, elem T) R) R {
334-
mut value := init
334+
mut value := R{}
335+
$if R is $array {
336+
value = init.clone()
337+
} $else {
338+
value = init
339+
}
335340

336341
for e in array {
337342
value = fold_op(value, e)

vlib/arrays/arrays_fold_test.v

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import arrays
2+
3+
type MyInt = int
4+
5+
fn test_main() {
6+
assert arrays.fold[int, []int]([1, 2, 3, 4], []int{}, fn (r []int, t int) []int {
7+
return arrays.merge(r, [t])
8+
}) == [1, 2, 3, 4]
9+
assert arrays.fold[string, []string](['a', 'b', 'c', 'd'], []string{}, fn (r []string, t string) []string {
10+
return arrays.merge(r, [t])
11+
}) == ['a', 'b', 'c', 'd']
12+
assert arrays.fold[bool, []bool]([true, false], []bool{}, fn (r []bool, t bool) []bool {
13+
return arrays.merge(r, [t])
14+
}) == [false, true]
15+
assert arrays.fold[MyInt, []MyInt]([MyInt(0), 1], []MyInt{}, fn (r []MyInt, t MyInt) []MyInt {
16+
return arrays.merge(r, [t])
17+
}) == [MyInt(0), 1]
18+
assert arrays.fold([1, 2, 3, 4], [5, 6, 7], fn (r []int, t int) []int {
19+
return r.map(it * t)
20+
}) == [120, 144, 168]
21+
}

0 commit comments

Comments
 (0)