Skip to content

Go 1.18+ polymorphic generic containers and functions.

License

Notifications You must be signed in to change notification settings

nwillc/genfuncs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

License CI codecov.io goreportcard.com Reference Mentioned in Awesome Go Releases

Genfuncs Package

Genfuncs implements various functions utilizing Go's Generics to help avoid writing boilerplate code, in particular when working with containers like heap, list, map, queue, set, slice, etc. Many of the functions are based on Kotlin's Sequence and Map. Some functional patterns like Result and Promises are presents. Attempts were also made to introduce more polymorphism into Go's containers. This package, while very usable, is primarily a proof-of-concept since it is likely Go will provide similar before long. In fact, golang.org/x/exp/slices and golang.org/x/exp/maps offer some similar functions and I incorporate them here.

Code Style

The coding style is not always idiomatic, in particular:

  • All functions have named return values and those variable are used in the return statements.
  • Some places where the range build-in could have been used instead use explicit indexing.

Both of these, while less idiomatic, were done because they measurably improve performance.

General notes:

  • A Map interface is provided to allow both Go's normal map and it's sync.Map to be used polymorphically.
  • The bias of these functions where appropriate is to be pure, without side effects, at the cost of copying data.
  • Examples are found in *examples_test.go files or projects like gordle, gorelease or gotimer.

License

The code is under the ISC License.

Requirements

Build with Go 1.18+

Getting

go get github.com/nwillc/genfuncs

Packages

genfuncs

import "github.com/nwillc/genfuncs"

Index

Variables

var (
    // Orderings
    LessThan    = -1
    EqualTo     = 0
    GreaterThan = 1

    // Predicates
    IsBlank    = OrderedEqualTo("")
    IsNotBlank = Not(IsBlank)
    F32IsZero  = OrderedEqualTo(float32(0.0))
    F64IsZero  = OrderedEqualTo(0.0)
    IIsZero    = OrderedEqualTo(0)
)
var (
    // PromiseNoActionErrorMsg indicates a Promise was created for no action.
    PromiseNoActionErrorMsg = "promise requested with no action"
    // PromisePanicErrorMsg indicates the action of a Promise caused a panic.
    PromisePanicErrorMsg = "promise action panic"
)
var IllegalArguments = fmt.Errorf("illegal arguments")

NoSuchElement error is used by panics when attempts are made to access out of bounds.

var NoSuchElement = fmt.Errorf("no such element")

func Empty

func Empty[T any]\(\) (empty T)

Empty return an empty value of type T.

func Max

func Max[T constraints.Ordered](v ...T) (max T)

Max returns max value one or more constraints.Ordered values,

Example

package main

import (
	"fmt"

	"github.com/nwillc/genfuncs"
)

func main() {
	fmt.Println(genfuncs.Max(1, 2))
	words := []string{"dog", "cat", "gorilla"}
	fmt.Println(genfuncs.Max(words...))
}

Output

2
gorilla

func Min

func Min[T constraints.Ordered](v ...T) (min T)

Min returns min value of one or more constraints.Ordered values,

Example

package main

import (
	"fmt"

	"github.com/nwillc/genfuncs"
)

func main() {
	fmt.Println(genfuncs.Min(1, 2))
	words := []string{"dog", "cat", "gorilla"}
	fmt.Println(genfuncs.Min(words...))
}

Output

1
cat

func Ordered

func Ordered[T constraints.Ordered](a, b T) (order int)

Ordered performs old school -1/0/1 comparison of constraints.Ordered arguments.

func OrderedEqual[O constraints.Ordered](a, b O) (orderedEqualTo bool)

OrderedEqual returns true jf a is ordered equal to b.

func OrderedGreater[O constraints.Ordered](a, b O) (orderedGreaterThan bool)

OrderedGreater returns true if a is ordered greater than b.

func OrderedLess[O constraints.Ordered](a, b O) (orderedLess bool)

OrderedLess returns true if a is ordered less than b.

BiFunction accepts two arguments and produces a result.

type BiFunction[T, U, R any] func(T, U) R
func TransformArgs[T1, T2, R any](transform Function[T1, T2], operation BiFunction[T2, T2, R]) (fn BiFunction[T1, T1, R])

TransformArgs uses the function to transform the arguments to be passed to the operation.

Example

package main

import (
	"fmt"
	"time"

	"github.com/nwillc/genfuncs"
)

func main() {
	var unixTime = func(t time.Time) int64 { return t.Unix() }
	var chronoOrder = genfuncs.TransformArgs(unixTime, genfuncs.OrderedLess[int64])
	now := time.Now()
	fmt.Println(chronoOrder(now, now.Add(time.Second)))
}

Output

true

Function is a single argument function.

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

func Curried

func Curried[A, R any](operation BiFunction[A, A, R], a A) (fn Function[A, R])

Curried takes a BiFunction and one argument, and Curries the function to return a single argument Function.

func Not

func Not[T any](predicate Function[T, bool]) (fn Function[T, bool])

Not takes a predicate returning and inverts the result.

func OrderedEqualTo[O constraints.Ordered](a O) (fn Function[O, bool])

OrderedEqualTo return a function that returns true if its argument is ordered equal to a.

func OrderedGreaterThan[O constraints.Ordered](a O) (fn Function[O, bool])

OrderedGreaterThan returns a function that returns true if its argument is ordered greater than a.

func OrderedLessThan[O constraints.Ordered](a O) (fn Function[O, bool])

OrderedLessThan returns a function that returns true if its argument is ordered less than a.

type Promise

Promise provides asynchronous Result of an action.

type Promise[T any] struct {
    // contains filtered or unexported fields
}
func NewPromise[T any](ctx context.Context, action func(context.Context) *Result[T]) *Promise[T]

NewPromise creates a Promise for an action.

func NewPromiseFromResult[T any](result *Result[T]) *Promise[T]

NewPromiseFromResult returns a completed Promise with the specified result.

func (*Promise[T]) Cancel

func (p *Promise[T]) Cancel()

Cancel the Promise which will allow any action that is listening on `<-ctx.Done()` to complete.

func (*Promise[T]) OnError

func (p *Promise[T]) OnError(action func(error)) *Promise[T]

OnError returns a new Promise with an error handler waiting on the original Promise.

func (*Promise[T]) OnSuccess

func (p *Promise[T]) OnSuccess(action func(t T)) *Promise[T]

OnSuccess returns a new Promise with a success handler waiting on the original Promise.

func (*Promise[T]) Wait

func (p *Promise[T]) Wait() *Result[T]

Wait on the completion of a Promise.

type Result

Result is an implementation of the Maybe pattern. This is mostly for experimentation as it is a poor fit with Go's traditional idiomatic error handling.

type Result[T any] struct {
    // contains filtered or unexported fields
}
func NewError[T any](err error) *Result[T]

NewError for an error.

func NewResult[T any](t T) *Result[T]

NewResult for a value.

func NewResultError[T any](t T, err error) *Result[T]

NewResultError creates a Result from a value, error tuple.

func (*Result[T]) Error

func (r *Result[T]) Error() error

Error of the Result, nil if Ok().

func (*Result[T]) MustGet

func (r *Result[T]) MustGet() T

MustGet returns the value of the Result if Ok() or if not, panics with the error.

func (*Result[T]) Ok

func (r *Result[T]) Ok() bool

Ok returns the status of Result, is it ok, or an error.

func (*Result[T]) OnError

func (r *Result[T]) OnError(action func(e error)) *Result[T]

OnError performs the action if Result is not Ok().

func (*Result[T]) OnSuccess

func (r *Result[T]) OnSuccess(action func(t T)) *Result[T]

OnSuccess performs action if Result is Ok().

func (*Result[T]) OrElse

func (r *Result[T]) OrElse(v T) T

OrElse returns the value of the Result if Ok(), or the value v if not.

func (*Result[T]) OrEmpty

func (r *Result[T]) OrEmpty() T

OrEmpty will return the value of the Result or the empty value if Error.

func (*Result[T]) String

func (r *Result[T]) String() string

String returns a string representation of Result, either the value or error.

func (*Result[T]) Then

func (r *Result[T]) Then(action func(t T) *Result[T]) *Result[T]

Then performs the action on the Result.

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

type ToString[T any] func(T) string
func StringerToString[T fmt.Stringer]() (fn ToString[T])

StringerToString creates a ToString for any type that implements fmt.Stringer.

Example

package main

import (
	"fmt"
	"time"

	"github.com/nwillc/genfuncs"
)

func main() {
	var epoch time.Time
	fmt.Println(epoch.String())
	stringer := genfuncs.StringerToString[time.Time]()
	fmt.Println(stringer(epoch))
}

Output

0001-01-01 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC

container

import "github.com/nwillc/genfuncs/container"

Index

Container is a minimal container that HasValues and accepts additional elements.

type Container[T any] interface {

    // Add an element to the Container.
    Add(t T)
    // AddAll elements to the Container.
    AddAll(t ...T)
    // contains filtered or unexported methods
}

type Deque

Deque is a doubly ended implementation of Queue with default behavior of a Fifo but provides left and right access. Employs a List for storage.

type Deque[T any] struct {
    // contains filtered or unexported fields
}
func NewDeque[T any](t ...T) (degue *Deque[T])

NewDeque creates a Deque containing any provided elements.

func (*Deque[T]) Add

func (d *Deque[T]) Add(t T)

Add an element to the right of the Deque.

func (*Deque[T]) AddAll

func (d *Deque[T]) AddAll(t ...T)

AddAll elements to the right of the Deque.

func (*Deque[T]) AddLeft

func (d *Deque[T]) AddLeft(t T)

AddLeft an element to the left of the Deque.

func (*Deque[T]) AddRight

func (d *Deque[T]) AddRight(t T)

AddRight an element to the right of the Deque.

func (*Deque[T]) Iterator

func (d *Deque[T]) Iterator() Iterator[T]

func (*Deque[T]) Len

func (d *Deque[T]) Len() (length int)

Len reports the length of the Deque.

func (*Deque[T]) Peek

func (d *Deque[T]) Peek() (value T)

Peek returns the left most element in the Deque without removing it.

func (*Deque[T]) PeekLeft

func (d *Deque[T]) PeekLeft() (value T)

PeekLeft returns the left most element in the Deque without removing it.

func (*Deque[T]) PeekRight

func (d *Deque[T]) PeekRight() (value T)

PeekRight returns the right most element in the Deque without removing it.

func (*Deque[T]) Remove

func (d *Deque[T]) Remove() (value T)

Remove and return the left most element in the Deque.

func (*Deque[T]) RemoveLeft

func (d *Deque[T]) RemoveLeft() (value T)

RemoveLeft and return the left most element in the Deque.

func (*Deque[T]) RemoveRight

func (d *Deque[T]) RemoveRight() (value T)

RemoveRight and return the right most element in the Deque.

func (*Deque[T]) Values

func (d *Deque[T]) Values() (values GSlice[T])

Values in the Deque returned in a new GSlice.

type GMap

GMap is a generic type employing the standard Go map and implementation Map.

type GMap[K comparable, V any] map[K]V

func (GMap[K, V]) All

func (m GMap[K, V]) All(predicate genfuncs.Function[V, bool]) (ok bool)

All returns true if all values in GMap satisfy the predicate.

func (GMap[K, V]) Any

func (m GMap[K, V]) Any(predicate genfuncs.Function[V, bool]) (ok bool)

Any returns true if any values in GMap satisfy the predicate.

func (GMap[K, V]) Contains

func (m GMap[K, V]) Contains(key K) (isTrue bool)

Contains returns true if the GMap contains the given key.

Example

package main

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

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

func main() {
	fmt.Println(wordPositions.Contains("hello"))
	fmt.Println(wordPositions.Contains("no"))
}

Output

true
false

func (GMap[K, V]) Delete

func (m GMap[K, V]) Delete(key K)

Delete an entry in the GMap.

func (GMap[K, V]) Filter

func (m GMap[K, V]) Filter(predicate genfuncs.Function[V, bool]) (result GMap[K, V])

Filter a GMap by a predicate, returning a new GMap that contains only values that satisfy the predicate.

func (GMap[K, V]) FilterKeys

func (m GMap[K, V]) FilterKeys(predicate genfuncs.Function[K, bool]) (result GMap[K, V])

FilterKeys returns a new GMap that contains only values whose key satisfy the predicate.

func (GMap[K, V]) ForEach

func (m GMap[K, V]) ForEach(action func(k K, v V))

ForEach performs the given action on each entry in the GMap.

func (GMap[K, V]) Get

func (m GMap[K, V]) Get(key K) (v V, ok bool)

Get returns an entry from the Map. The returned bool indicates if the key is in the Map.

func (GMap[K, V]) GetOrElse

func (m GMap[K, V]) GetOrElse(k K, defaultValue func() V) (value V)

GetOrElse returns the value at the given key if it exists or returns the result of defaultValue.

func (GMap[K, V]) Iterator

func (m GMap[K, V]) Iterator() Iterator[V]

Iterator creates an iterator for the values in the GMap.

func (GMap[K, V]) Keys

func (m GMap[K, V]) Keys() (keys GSlice[K])

Keys return a GSlice containing the keys of the GMap.

Example

package main

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

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

func main() {
	fmt.Println(wordPositions.Keys().SortBy(genfuncs.OrderedLess[string]))
}

Output

[hello world]

func (GMap[K, V]) Len

func (m GMap[K, V]) Len() (length int)

Len is the number of elements in the GMap.

func (GMap[K, V]) Put

func (m GMap[K, V]) Put(key K, value V)

Put a key and value in the Map.

func (GMap[K, V]) Values

func (m GMap[K, V]) Values() (values GSlice[V])

Values returns a GSlice of all the values in the GMap.

Example

package main

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

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

func main() {
	wordPositions.Values().ForEach(func(_, i int) { fmt.Println(i) })
}

Output

1
2

type GSlice

GSlice is a generic type corresponding to a standard Go slice that implements HasValues.

type GSlice[T any] []T

func (GSlice[T]) Filter

func (s GSlice[T]) Filter(predicate genfuncs.Function[T, bool]) GSlice[T]

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

Example

package main

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

var isGreaterThanZero = genfuncs.OrderedGreaterThan(0)

func main() {
	var values container.GSlice[int] = []int{1, -2, 2, -3}
	values.Filter(isGreaterThanZero).ForEach(func(_, i int) {
		fmt.Println(i)
	})
}

Output

1
2

func (GSlice[T]) ForEach

func (s GSlice[T]) ForEach(action func(i int, t T))

ForEach element of the GSlice invoke given function with the element. Syntactic sugar for a range that intends to traverse all the elements, i.e. no exiting midway through.

func (GSlice[T]) Iterator

func (s GSlice[T]) Iterator() Iterator[T]

Iterator returns an Iterator that will iterate over the GSlice.

func (GSlice[T]) Len

func (s GSlice[T]) Len() int

Len is the number of elements in the GSlice.

func (GSlice[T]) Random

func (s GSlice[T]) Random() (t T)

Random returns a random element of the GSlice.

func (GSlice[T]) SortBy

func (s GSlice[T]) SortBy(order genfuncs.BiFunction[T, T, bool]) (sorted GSlice[T])

SortBy copies a slice, sorts the copy applying the Ordered and returns it. This is not a pure function, the GSlice is sorted in place, the returned slice is to allow for fluid calls in chains.

Example

package main

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

func main() {
	var numbers container.GSlice[int] = []int{1, 0, 9, 6, 0}
	fmt.Println(numbers)
	fmt.Println(numbers.SortBy(genfuncs.OrderedLess[int]))
}

Output

[1 0 9 6 0]
[0 0 1 6 9]

func (GSlice[T]) Swap

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

Swap two values in the slice.

Example

package main

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

var words container.GSlice[string] = []string{"hello", "world"}

func main() {
	words = words.SortBy(genfuncs.OrderedLess[string])
	words.Swap(0, 1)
	fmt.Println(words)
}

Output

[world hello]

func (GSlice[T]) Values

func (s GSlice[T]) Values() (values GSlice[T])

Values is the GSlice itself.

HasValues is an interface that indicates a struct contains values that can counted and be retrieved.

type HasValues[T any] interface {
    // Len returns length of the Container.
    Len() int
    // Values returns a copy of the current values in the Container without modifying the contents.
    Values() GSlice[T]
}

type Heap

Heap implements an ordered heap of any type which can be min heap or max heap depending on the compare provided. Heap implements Queue.

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

func NewHeap

func NewHeap[T any](compare genfuncs.BiFunction[T, T, bool], values ...T) (heap *Heap[T])

NewHeap return a heap ordered based on the compare and adds any values provided.

Example

package main

import (
	"fmt"

	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
)

func main() {
	heap := container.NewHeap[int](genfuncs.OrderedLess[int], 3, 1, 4, 2)
	for heap.Len() > 0 {
		fmt.Print(heap.Remove())
	}
	fmt.Println()
}

Output

1234

func (*Heap[T]) Add

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

Add a value onto the heap.

func (*Heap[T]) AddAll

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

AddAll the values onto the Heap.

func (*Heap[T]) Len

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

Len returns current length of the heap.

func (*Heap[T]) Peek

func (h *Heap[T]) Peek() (value T)

Peek returns the next element without removing it.

func (*Heap[T]) Remove

func (h *Heap[T]) Remove() (value T)

Remove an item off the heap.

func (*Heap[T]) Values

func (h *Heap[T]) Values() (values GSlice[T])

Values returns a slice of the values in the Heap in no particular order.

type Iterator[T any] interface {
    HasNext() bool
    Next() T
}
func NewListIterator[T any](list *List[T]) Iterator[T]
func NewSliceIterator[T any](slice []T) Iterator[T]
func NewValuesIterator[T any](values ...T) Iterator[T]

type List

List is a doubly linked list, inspired by list.List but reworked to be generic. List implements Container.

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

func NewList

func NewList[T any](values ...T) (l *List[T])

NewList instantiates a new List containing any values provided.

func (*List[T]) Add

func (l *List[T]) Add(value T)

Add a value to the right of the List.

func (*List[T]) AddAll

func (l *List[T]) AddAll(values ...T)

AddAll values to the right of the List.

func (*List[T]) AddLeft

func (l *List[T]) AddLeft(value T) (e *ListElement[T])

AddLeft adds a value to the left of the List.

func (*List[T]) AddRight

func (l *List[T]) AddRight(v T) (e *ListElement[T])

AddRight adds a value to the right of the List.

func (*List[T]) ForEach

func (l *List[T]) ForEach(action func(value T))

ForEach invokes the action for each value in the list.

func (*List[T]) Iterator

func (l *List[T]) Iterator() Iterator[T]

Iterator creates an Iterator for the List.

func (*List[T]) Len