mirror of
https://github.com/vlang/v.git
synced 2025-09-12 00:46:55 -04:00
arrays: fix arrays.fold, when the init
value in the call, is an array (#21921)
This commit is contained in:
parent
b5ba466488
commit
d186c3946f
@ -331,7 +331,12 @@ pub fn filter_indexed[T](array []T, predicate fn (idx int, elem T) bool) []T {
|
||||
// assert r == 5
|
||||
// ```
|
||||
pub fn fold[T, R](array []T, init R, fold_op fn (acc R, elem T) R) R {
|
||||
mut value := init
|
||||
mut value := R{}
|
||||
$if R is $array {
|
||||
value = init.clone()
|
||||
} $else {
|
||||
value = init
|
||||
}
|
||||
|
||||
for e in array {
|
||||
value = fold_op(value, e)
|
||||
|
21
vlib/arrays/arrays_fold_test.v
Normal file
21
vlib/arrays/arrays_fold_test.v
Normal file
@ -0,0 +1,21 @@
|
||||
import arrays
|
||||
|
||||
type MyInt = int
|
||||
|
||||
fn test_main() {
|
||||
assert arrays.fold[int, []int]([1, 2, 3, 4], []int{}, fn (r []int, t int) []int {
|
||||
return arrays.merge(r, [t])
|
||||
}) == [1, 2, 3, 4]
|
||||
assert arrays.fold[string, []string](['a', 'b', 'c', 'd'], []string{}, fn (r []string, t string) []string {
|
||||
return arrays.merge(r, [t])
|
||||
}) == ['a', 'b', 'c', 'd']
|
||||
assert arrays.fold[bool, []bool]([true, false], []bool{}, fn (r []bool, t bool) []bool {
|
||||
return arrays.merge(r, [t])
|
||||
}) == [false, true]
|
||||
assert arrays.fold[MyInt, []MyInt]([MyInt(0), 1], []MyInt{}, fn (r []MyInt, t MyInt) []MyInt {
|
||||
return arrays.merge(r, [t])
|
||||
}) == [MyInt(0), 1]
|
||||
assert arrays.fold([1, 2, 3, 4], [5, 6, 7], fn (r []int, t int) []int {
|
||||
return r.map(it * t)
|
||||
}) == [120, 144, 168]
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user