Go 1.18 generics based slice and sorts.

License Releases

genfuncs

import "github.com/nwillc/genfuncs"

Package genfuncs implements various functions utilizing Go's Generics to help avoid writing boilerplate code, in particular when working with slices. Many of the functions are based on Kotlin's Sequence. This package, though usable, is primarily a proof-of-concept since it is likely Go will provide similar at some point soon.

The code is under the ISC License: https://github.com/nwillc/genfuncs/blob/master/LICENSE.md

Index

func Associate

func Associate[T, V any, K comparable](slice []T, keyValueFor KeyValueFor[T, K, V]) map[K]V

Associate returns a map containing key/values created by applying a function to elements of the slice.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"strings"
)

func main() {
	byLastName := func(n string) (string, string) {
		parts := strings.Split(n, " ")
		return parts[1], n
	}
	names := []string{"fred flintstone", "barney rubble"}
	nameMap := genfuncs.Associate(names, byLastName)
	fmt.Println(nameMap["rubble"]) // barney rubble
}

func AssociateWith

func AssociateWith[K comparable, V any](slice []K, valueFor ValueFor[K, V]) map[K]V

AssociateWith returns a Map where keys are elements from the given sequence and values are produced by the valueSelector function applied to each element.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

func main() {
	oddEven := func(i int) string {
		if i%2 == 0 {
			return "EVEN"
		}
		return "ODD"
	}
	numbers := []int{1, 2, 3, 4}
	odsEvensMap := genfuncs.AssociateWith(numbers, oddEven)
	fmt.Println(odsEvensMap[2]) // EVEN
	fmt.Println(odsEvensMap[3]) // ODD
}

func Distinct

func Distinct[T comparable](slice []T) []T

Distinct returns a slice containing only distinct elements from the given slice.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

func main() {
	values := []int{1, 2, 2, 3, 1, 3}
	fmt.Println(genfuncs.Distinct(values)) // [1 2 3]
}

func FlatMap

func FlatMap[T, R any](slice []T, function Function[T, []R]) []R

FlatMap returns a slice of all elements from results of transform function being invoked on each element of original slice, and those resultant slices concatenated.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"strings"
)

var lexicalOrder = genfuncs.OrderedComparator[string]()

var words genfuncs.Slice[string] = []string{"hello", "world"}

func main() {
	slicer := func(s string) []string { return strings.Split(s, "") }
	fmt.Println(genfuncs.FlatMap(words.SortBy(lexicalOrder), slicer)) // [h e l l o w o r l d]
}

func Fold

func Fold[T, R any](slice []T, initial R, biFunction BiFunction[R, T, R]) R

Fold accumulates a value starting with initial value and applying operation from left to right to current accumulated value and each element.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

func main() {
	numbers := []int{1, 2, 3, 4, 5}
	sum := func(a int, b int) int { return a + b }
	fmt.Println(genfuncs.Fold(numbers, 0, sum)) // 15
}

func GroupBy

func GroupBy[T any, K comparable](slice []T, keyFor KeyFor[T, K]) map[K][]T

GroupBy groups elements of the slice by the key returned by the given keySelector function applied to each element and returns a map where each group key is associated with a slice of corresponding elements.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

func main() {
	oddEven := func(i int) string {
		if i%2 == 0 {
			return "EVEN"
		}
		return "ODD"
	}
	numbers := []int{1, 2, 3, 4}
	grouped := genfuncs.GroupBy(numbers, oddEven)
	fmt.Println(grouped["ODD"]) // [1 3]
}

func Keys

func Keys[K comparable, V any](m map[K]V) []K

Keys returns a slice of all the keys in the map.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

var wordPositions = map[string]int{"hello": 1, "world": 2}

func main() {
	keys := genfuncs.Keys(wordPositions)
	fmt.Println(keys) // [hello, world]
}

func Map

func Map[T, R any](slice []T, function Function[T, R]) []R

Map returns a slice containing the results of applying the given transform function to each element in the original slice.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

func main() {
	numbers := []int{69, 88, 65, 77, 80, 76, 69}
	toString := func(i int) string { return string(rune(i)) }
	fmt.Println(genfuncs.Map(numbers, toString)) // [E X A M P L E]
}

func Values

func Values[K comparable, V any](m map[K]V) []V

Values returns a slice of all the values in the map.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

var wordPositions = map[string]int{"hello": 1, "world": 2}

func main() {
	values := genfuncs.Values(wordPositions)
	fmt.Println(values) // [1, 2]
}

type BiFunction

BiFunction accepts two arguments and produces a result.

type BiFunction[T, U, R any] func(T, U) R

type Comparator

Comparator compares two arguments of the same type and returns LessThan, EqualTo or GreaterThan based relative order.

type Comparator[T any] BiFunction[T, T, Ordering]

func FunctionComparator

func FunctionComparator[T, R any](transform Function[T, R], comparator Comparator[R]) Comparator[T]

FunctionComparator composites an existing Comparator[R] and Function[T,R] into a new Comparator[T].

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"time"
)

func main() {
	var unixTime = func(t time.Time) int64 { return t.Unix() }
	var timeComparator = genfuncs.FunctionComparator(unixTime, genfuncs.OrderedComparator[int64]())

	now := time.Now()
	fmt.Println(timeComparator(now, now.Add(time.Second))) // -1
}

func OrderedComparator

func OrderedComparator[T constraints.Ordered]() Comparator[T]

OrderedComparator will create a Comparator from any type included in the constraints.Ordered constraint.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

var lexicalOrder = genfuncs.OrderedComparator[string]()

func main() {
	fmt.Println(lexicalOrder("a", "b")) // -1
	fmt.Println(lexicalOrder("a", "a")) // 0
	fmt.Println(lexicalOrder("b", "a")) // 1
}

func ReverseComparator

func ReverseComparator[T any](comparator Comparator[T]) Comparator[T]

ReverseComparator reverses a Comparator to facilitate switching sort orderings.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

var lexicalOrder = genfuncs.OrderedComparator[string]()
var reverseLexical = genfuncs.ReverseComparator(lexicalOrder)

func main() {
	fmt.Println(lexicalOrder("a", "b"))   // -1
	fmt.Println(reverseLexical("a", "b")) // 1
}

type Function

Function accepts one argument and produces a result.

type Function[T, R any] func(T) R

type Heap

Heap implements either a min or max ordered heap of any type.

type Heap[T any] struct {
    // contains filtered or unexported fields
}

func NewHeap

func NewHeap[T any](comparator Comparator[T]) *Heap[T]

NewHeap return a heap ordered based on the Comparator.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
)

var intCmp = genfuncs.OrderedComparator[int]()

func main() {
	heap := genfuncs.NewHeap(intCmp)
	heap.PushAll(3, 1, 4, 2)
	for heap.Len() > 0 {
		fmt.Print(heap.Pop()) // 1234
	}
	fmt.Println()
}

func (*Heap) Len

func (h *Heap[T]) Len() int

Len returns current length of the heap.

func (*Heap) Pop

func (h *Heap[T]) Pop() T

Pop an item off the heap.

func (*Heap) Push

func (h *Heap[T]) Push(v T)

Push a value onto the heap.

func (*Heap) PushAll

func (h *Heap[T]) PushAll(values ...T)

PushAll the values onto the Heap.

type KeyFor

KeyFor is used for generating keys from types, it accepts any type and returns a comparable key for it.

type KeyFor[T any, K comparable] Function[T, K]

type KeyValueFor

KeyValueFor is used to generate a key and value from a type, it accepts any type, and returns a comparable key and any value.

type KeyValueFor[T any, K comparable, V any] func(T) (K, V)

type Ordering

Ordering is the type returned by a Comparator.

type Ordering int
var (
    LessThan    Ordering = -1
    EqualTo     Ordering = 0
    GreaterThan Ordering = 1
)

type Predicate

Predicate is used evaluate a value, it accepts any type and returns a bool.

type Predicate[T any] func(T) bool

func IsEqualTo

func IsEqualTo[T comparable](a T) Predicate[T]

IsEqualTo creates a Predicate that tests if its argument is equal to a given value.

func IsGreaterThan

func IsGreaterThan[T constraints.Ordered](a T) Predicate[T]

IsGreaterThan creates a Predicate that tests if its argument is greater than a given value.

func IsLessThan

func IsLessThan[T constraints.Ordered](a T) Predicate[T]

IsLessThan creates a Predicate that tests if its argument is less than a given value.

type Slice

type Slice[T any] []T

func (Slice) All

func (s Slice[T]) All(predicate Predicate[T]) bool

All returns true if all elements of slice match the predicate.

func (Slice) Any

func (s Slice[T]) Any(predicate Predicate[T]) bool

Any returns true if any element of the slice matches the predicate.

func (Slice) Contains

func (s Slice[T]) Contains(element T, comparator Comparator[T]) bool

Contains returns true if element is found in slice.

func (Slice) Filter

func (s Slice[T]) Filter(predicate Predicate[T]) Slice[T]

Filter returns a slice containing only elements matching the given predicate.

func (Slice) Find

func (s Slice[T]) Find(predicate Predicate[T]) (T, bool)

Find returns the first element matching the given predicate and true, or false when no such element was found.

func (Slice) FindLast

func (s Slice[T]) FindLast(predicate Predicate[T]) (T, bool)

FindLast returns the last element matching the given predicate and true, or false when no such element was found.

func (Slice) JoinToString

func (s Slice[T]) JoinToString(stringer Stringer[T], separator string, prefix string, postfix string) string

JoinToString creates a string from all the elements using the stringer on each, separating them using separator, and using the given prefix and postfix.

func (Slice) Sort

func (s Slice[T]) Sort(comparator Comparator[T])

Sort sorts a slice by Comparator order.

func (Slice) SortBy

func (s Slice[T]) SortBy(comparator Comparator[T]) []T

SortBy copies a slice, sorts the copy applying the Comparator and returns it.

func (Slice) Swap

func (s Slice[T]) Swap(i, j int)

Swap two values in the slice.

type Stringer

Stringer is used to create string representations, it accepts any type and returns a string.

type Stringer[T any] func(T) string

func StringerStringer

func StringerStringer[T fmt.Stringer]() Stringer[T]

StringerStringer creates a Stringer for any type that implements fmt.Stringer.

Example

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"time"
)

func main() {
	var epoch time.Time
	fmt.Println(epoch.String()) // 0001-01-01 00:00:00 +0000 UTC
	stringer := genfuncs.StringerStringer[time.Time]()
	fmt.Println(stringer(epoch)) // 0001-01-01 00:00:00 +0000 UTC
}

type ValueFor

ValueFor given a comparable key will return a value for it.

type ValueFor[K comparable, T any] Function[K, T]

Generated by gomarkdoc

Owner
Nwillc
I'm a graybeard software engineer. Been coding since high school in the 1980's.  I've been doing it professionally since college.
Nwillc
Similar Resources

CDN-like in-memory cache with shielding, and Go 1.18 Generics

cache CDN-like, middleware memory cache for Go applications with integrated shielding and Go 1.18 Generics. Usage package main import ( "context" "

Apr 26, 2022

Experiments with Go generics

generics Quick experiments with Go generics algebra, a generic square root function for float, complex and and rational. future, a concurrent cache ("

Dec 31, 2022

Example code for Go generics

go-generics-example Example code for Go generics. Usage $ go build -gcflags=-G=3 Requirements Go 1.17 or later Advertise Go 言語にやってくる Generics は我々に何をも

Dec 30, 2022

Collection of unusual generics usecases in Go

Unusual Generics Type parameters or Generics in Go designed to reduce boilerplate for container data types like lists, graphs, etc. and functions like

Dec 14, 2022

Package truthy provides truthy condition testing with Go generics

Package truthy provides truthy condition testing with Go generics

Truthy Truthy is a package which uses generics (Go 1.18+) to create useful boolean tests and helper functions. Examples // truthy.Value returns the tr

Nov 11, 2022

Go Library for Competitive Programming with Generics

Go Library for Competitive Programming with Generics Go used to be a difficult language to use for competitive programming. However, with the introduc

Dec 21, 2022

Extended library functions using generics in Go.

Just few extended standard library functions for Golang using generics.

Dec 16, 2021

A library that provides Go Generics friendly "optional" features.

go-optional A library that provides Go Generics friendly "optional" features. Synopsis some := optional.Some[int](123) fmt.Printf("%v\n", some.IsSome(

Dec 20, 2022

experimental promises in go1.18 with generics

async go a prototype of "promises" in go1.18. note: this is just an experiment used to test alternate patterns for dealing with asynchronous code in g

Dec 23, 2022
🍕 Enjoy a slice! A utility library for dealing with slices and maps that focuses on type safety and performance.

?? github.com/elliotchance/pie Enjoy a slice! pie is a library of utility functions for common operations on slices and maps. Quick Start FAQ What are

Dec 30, 2022
💪 Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more.
💪 Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more.

?? Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more. Go 的一些工具函数,格式化,特殊处理,常用信息获取等等

Jan 6, 2023
Tiny Go tool for running multiple functions concurrently and collecting their results into an error slice.

Overview Short for "ConCurrent". Tiny Go tool for running multiple functions concurrently and collecting their results into an error slice. Dependency

Nov 22, 2021
Wrap byte read options with uniform interface for io.Reader and byte slice

nibbler Nibble chunks from Reader streams and slice in a common way Overview This is a golang module that provides an interface for treating a Reader

Dec 23, 2021
Slice - provides generic Map, Reduce and Filter functions for Go.

slice slice is a simple Go package to provide generic versions of Map, Reduce and Filter on slices. I mainly wrote it as an exercise to get more famil

Jan 1, 2023
Goety - Generics based Go utilities

goety General purpose Go utilities. Package channel Utilities to work with chann

May 16, 2022
make slice items unique in go

make slice items unique in go

Jan 20, 2022
Slice conversion between primitive types

sliceconv Sliceconv implements conversions to and from string representations of primitive types on entire slices. The package supports types int, flo

Sep 27, 2022
Code Generation for Functional Programming, Concurrency and Generics in Golang

goderive goderive derives mundane golang functions that you do not want to maintain and keeps them up to date. It does this by parsing your go code fo

Dec 25, 2022
Go 1.18 generics use cases and examples

Go 1.18 generics use cases What are generics? See Type Parameters Proposal. How to run the examples? As of today, gotip is the simplest way to run the

Jan 10, 2022