diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 34e0a330a6..eea38bb19a 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -354,3 +354,20 @@ pub fn (a []int) filter(predicate fn(p_val int, p_i int, p_arr []int) bool) []in } return res } + +////////////// REDUCE ////////////// + +// method executes a reducer function (that you provide) on each element of the array, +// resulting in a single output value. +pub fn (a []int) reduce( + iter fn (accum int, curr int) int, + accum_start int +) int +{ + mut _accum := 0 + _accum = accum_start + for i := 0; i < a.len; i++ { + _accum = iter(_accum, a[i]) + } + return _accum +} diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index 6552c59327..49d01dd3cf 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -314,3 +314,27 @@ fn test_filter() { assert d[0] == 'is' assert d[1] == 'awesome' } + +fn sum(prev int, curr int) int { + return prev + curr +} + +fn sub(prev int, curr int) int { + return prev - curr +} + +fn test_reduce() { + a := [1, 2, 3, 4, 5] + b := a.reduce(sum, 0) + c := a.reduce(sum, 5) + d := a.reduce(sum, -1) + assert b == 15 + assert c == 20 + assert d == 14 + + e := [1, 2, 3] + f := e.reduce(sub, 0) + g := e.reduce(sub, -1) + assert f == -6 + assert g == -7 +}