generics

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2024 License: Apache-2.0 Imports: 1 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrDifferentLength = errors.New("arrays must be the same length")
)

Functions

func Apply

func Apply[A any](f func(A) error, arr []A) []error

Apply applies a function to each element of an array

It returns an array of errors, where each error corresponds to the result of the function applied to the element at the same index

It returns nil if all function calls return nil

Example
arr := []int{1, 2, 3, 4, 5}
errs := Apply(func(a int) error {
	if a%2 == 0 {
		return nil
	}
	return errors.New("testErr")
}, arr)

if errs != nil {
	fmt.Println(errs)
}
Output:

[testErr <nil> testErr <nil> testErr]

func Map

func Map[A any, B any](f func(A) (B, error), arr []A) ([]B, []error)

Map applies a function to each element of an array

It returns an array of results and an array of errors, where each result and error corresponds to the result of the function applied to the element at the same index

It returns nil if all function calls return nil

Example
arr := []int{1, 2, 3, 4, 5}
doubled, err := Map(func(a int) (int, error) {
	return a * 2, nil
}, arr)

if err != nil {
	fmt.Println(err)
}

fmt.Println(doubled)
Output:

[2 4 6 8 10]

Types

type Pair

type Pair[A, B any] struct {
	A A
	B B
}

func Zip

func Zip[A any, B any](a []A, b []B) ([]Pair[A, B], error)
Example
arr1 := []int{1, 2, 3, 4, 5}
arr2 := []int{5, 4, 3, 2, 1}

zipped, err := Zip(arr1, arr2)

if err != nil {
	fmt.Println(err)
}

fmt.Println(zipped)
Output:

[{1 5} {2 4} {3 3} {4 2} {5 1}]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL