From 54de04a916806a92a4d8ce70bd827bb66a612d47 Mon Sep 17 00:00:00 2001 From: Nick Treleaven Date: Wed, 9 Mar 2022 18:04:49 +0000 Subject: [PATCH] arrays: improve fold/reduce docs (#13700) --- vlib/arrays/arrays.v | 20 +++++++++++++++----- vlib/builtin/array.v | 3 ++- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/vlib/arrays/arrays.v b/vlib/arrays/arrays.v index cacd9906df..23b90c7ef8 100644 --- a/vlib/arrays/arrays.v +++ b/vlib/arrays/arrays.v @@ -218,8 +218,10 @@ pub fn sum(list []T) ?T { } } -// accumulates values with the first element and applying providing operation to current accumulator value and each elements. -// If the array is empty, then returns error. +// reduce sets `acc = list[0]`, then successively calls `acc = reduce_op(acc, elem)` for each remaining element in `list`. +// returns the accumulated value in `acc`. +// returns an error if the array is empty. +// See also: [fold](#fold). // Example: arrays.reduce([1, 2, 3, 4, 5], fn (t1 int, t2 int) int { return t1 * t2 })? // => 120 pub fn reduce(list []T, reduce_op fn (t1 T, t2 T) T) ?T { if list.len == 0 { @@ -239,8 +241,16 @@ pub fn reduce(list []T, reduce_op fn (t1 T, t2 T) T) ?T { } } -// accumulates values with providing initial value and applying providing operation to current accumulator value and each elements. -// Example: arrays.fold(['H', 'e', 'l', 'l', 'o'], 0, fn (r int, t string) int { return r + t[0] }) // => 149 +// fold sets `acc = init`, then successively calls `acc = fold_op(acc, elem)` for each element in `list`. +// returns `acc`. +// Example: +// ```v +// // Sum the length of each string in an array +// a := ['Hi', 'all'] +// r := arrays.fold(a, 0, +// fn (r int, t string) int { return r + t.len }) +// assert r == 5 +// ``` pub fn fold(list []T, init R, fold_op fn (r R, t T) R) R { mut value := init @@ -275,7 +285,7 @@ pub fn flatten(list [][]T) []T { return result } -// grouping list of elements with given key selector. +// group_by groups together elements, for which the `grouping_op` callback produced the same result. // Example: arrays.group_by(['H', 'el', 'lo'], fn (v string) int { return v.len }) // => {1: ['H'], 2: ['el', 'lo']} pub fn group_by(list []V, grouping_op fn (v V) K) map[K][]V { mut result := map[K][]V{} diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 50e927ead6..4c7620251a 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -826,7 +826,8 @@ pub fn copy(dst []byte, src []byte) int { // reduce executes a given reducer function on each element of the array, // resulting in a single output value. -// NOTE: It exists as a method on `[]int` types only +// NOTE: It exists as a method on `[]int` types only. +// See also `arrays.fold`. pub fn (a []int) reduce(iter fn (int, int) int, accum_start int) int { mut accum_ := accum_start for i in a {