Documentation ¶
Overview ¶
package funcy implements functional favorites like filter, map, and reduce.
You'll get a compile error if you try something that doesn't make sense. For example, using map to run strings.ToLower on a slice of ints:
sl := []int{1, 2, 3, 4} result := Map(sl, strings.ToLower)
will get you an error like
pkg/funcy_test.go:64:20: type func(s string) string of strings.ToLower does not match inferred type func(int) T2 for func(T1) T2
Index ¶
- func Filter[T any](sl []T, test func(T) bool) []T
- func FilterWithIndex[T any](sl []T, test func(int, T) bool) []T
- func Map[T1, T2 any](sl []T1, transform func(T1) T2) []T2
- func MustTranspose[T any](sl [][]T) [][]T
- func Reduce[T1, T2 any](sl []T1, startValue T2, fReduce func(T2, T1) T2) T2
- func Sum[T constraints.Ordered](sl []T) T
- func Transpose[T any](sl [][]T) ([][]T, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Filter ¶
Filter takes a slice of any type and a predicate function. It passes each slice item to the predicate function, and returns a slice of the items for which the predicate function returns true.
func FilterWithIndex ¶
FilterWithIndex is like Filter, but the predicate function receives two arguments. The second argument is the slice item; the first argument is the item's index within the slice. FilterWithIndex returns a list of the items for which the predicate function returns true.
func Map ¶
func Map[T1, T2 any](sl []T1, transform func(T1) T2) []T2
Map runs each item in a slice through a transformation function, and returns a slice of the transformed items. The transformed items may be a different type from the input items, e.g. strings to ints using strconv.Atoi.
Note: For functions that return multiple values, like strconv.Atoi, wrap the function in another function that returns a single value, and pass the wrapper as the transformation function. The wrapper can handle errors, etc.:
result := Map(input, func(s string) int { i, err := strconv.Atoi(s) if err != nil { log.Fatal(err) } return i })
func MustTranspose ¶
func MustTranspose[T any](sl [][]T) [][]T
MustTranspose calls Transpose and panics on error.
func Reduce ¶
func Reduce[T1, T2 any](sl []T1, startValue T2, fReduce func(T2, T1) T2) T2
Reduce reduces a slice to a single value by running each item of the slice through a function that takes an accumulator and the next item as its paramaters. The classic example is reducing a slice of numbers by adding them together.
Types ¶
This section is empty.