fn

package module
v2.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2024 License: MIT Imports: 13 Imported by: 1

Documentation

Overview

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Index

Constants

View Source
const (
	// DefaultQueueSize is the default size to use for concurrent queues.
	DefaultQueueSize = 10
)

Variables

View Source
var (
	// DefaultTimeout is the default timeout used for context operations.
	DefaultTimeout = 30 * time.Second
)

Functions

func All

func All[A any](s []A, pred Pred[A]) bool

All returns true when the supplied predicate evaluates to true for all of the values in the slice.

func Any

func Any[A any](s []A, pred Pred[A]) bool

Any returns true when the supplied predicate evaluates to true for any of the values in the slice.

func Comp

func Comp[A, B, C any](f func(A) B, g func(B) C) func(A) C

Comp is left to right function composition. Comp(f, g)(x) == g(f(x)). This can make it easier to create on the fly closures that we may use as arguments to other functions defined in this package (or otherwise).

func Const

func Const[B, A any](a A) func(B) A

Const is a function that accepts an argument and returns a function that always returns that value irrespective of the returned function's argument. This is also quite useful in conjunction with higher order functions.

func CopyAll added in v2.0.3

func CopyAll[T Copyable[T]](xs []T) []T

CopyAll creates a new slice where each item of the slice is a deep copy of the elements of the input slice.

func CopyAllErr added in v2.0.3

func CopyAllErr[T CopyableErr[T]](xs []T) ([]T, error)

CopyAllErr creates a new slice where each item of the slice is a deep copy of the elements of the input slice. This is identical to CopyAll, but should be used in cases where the copy method can return an error.

func Elem

func Elem[A comparable](a A, s []A) bool

Elem returns true if the element in the argument is found in the slice

func ElimEither

func ElimEither[L, R, O any](e Either[L, R], f func(L) O, g func(R) O) O

ElimEither is the universal Either eliminator. It can be used to safely handle all possible values inside the Either by supplying two continuations, one for each side of the Either.

func ElimOption

func ElimOption[A, B any](o Option[A], b func() B, f func(A) B) B

ElimOption is the universal Option eliminator. It can be used to safely handle all possible values inside the Option by supplying two continuations.

ElimOption : (Option[A], () -> B, A -> B) -> B.

func Eq

func Eq[A comparable](x A) func(A) bool

Eq is a curried function that returns true if its eventual two arguments are equal.

func Filter

func Filter[A any](s []A, pred Pred[A]) []A

Filter creates a new slice of values where all the members of the returned slice pass the predicate that is supplied in the argument.

func FilterMap

func FilterMap[A, B any](as []A, f func(A) Option[B]) []B

FilterMap takes a function argument that optionally produces a value and returns a slice of the 'Some' return values.

func FlatMapOption

func FlatMapOption[A, B any](f func(A) Option[B]) func(Option[A]) Option[B]

FlatMapOption transforms a function A -> Option[B] into one that accepts an Option[A] as an argument.

FlatMapOption : (A -> Option[B]) -> Option[A] -> Option[B].

func Flatten

func Flatten[A any](s [][]A) []A

Flatten takes a slice of slices and returns a concatenation of those slices.

func Foldl

func Foldl[A, B any](seed B, s []A, f func(B, A) B) B

Foldl iterates through all members of the slice left to right and reduces them pairwise with an accumulator value that is seeded with the seed value in the argument.

func Foldr

func Foldr[A, B any](seed B, s []A, f func(A, B) B) B

Foldr, is exactly like Foldl except that it iterates over the slice from right to left.

func ForEachConc

func ForEachConc[A, B any](as []A, f func(A) B) []B

ForEachConc maps the argument function over the slice, spawning a new goroutine for each element in the slice and then awaits all results before returning them.

func GuardTest added in v2.0.5

func GuardTest(t *testing.T, opts ...GuardOption) func()

GuardTest implements a test level timeout.

func HasDuplicates

func HasDuplicates[A comparable](items []A) bool

HasDuplicates checks if the given slice contains any duplicate elements. It returns false if there are no duplicates in the slice (i.e., all elements are unique), otherwise returns false.

func Iden

func Iden[A any](a A) A

Iden is the left and right identity of Comp. It is a function that simply returns its argument. The utility of this function is only apparent in conjunction with other functions in this package.

func Len

func Len[A any](items []A) uint

Len is the len function that is defined in a way that makes it usable in higher-order contexts.

func LiftA2Option

func LiftA2Option[A, B, C any](
	f func(A, B) C,
) func(Option[A], Option[B]) Option[C]

LiftA2Option transforms a pure function (A, B) -> C into one that will operate in an Option context. For the returned function, if either of its arguments are None, then the result will be None.

LiftA2Option : ((A, B) -> C) -> (Option[A], Option[B]) -> Option[C].

func LiftA2Result

func LiftA2Result[A, B, C any](f func(A, B) C,
) func(Result[A], Result[B]) Result[C]

LiftA2Result lifts a two-argument function to a function that can operate over results of its arguments.

func Map

func Map[A, B any](s []A, f func(A) B) []B

Map applies the function argument to all members of the slice and returns a slice of those return values.

func MapFirst

func MapFirst[A, B, C any](f func(A) B) func(T2[A, C]) T2[B, C]

MapFirst lifts the argument function into one that applies to the first element of a 2-tuple.

func MapLeft

func MapLeft[L, R, O any](f func(L) O) func(Either[L, R]) Either[O, R]

MapLeft maps the left value of the Either to a new value.

func MapOk

func MapOk[A, B any](f func(A) B) func(Result[A]) Result[B]

MapOk applies a non-endomorphic function to the success value if it exists and returns a Result of the new type.

func MapOption

func MapOption[A, B any](f func(A) B) func(Option[A]) Option[B]

MapOption transforms a pure function A -> B into one that will operate inside the Option context.

MapOption : (A -> B) -> Option[A] -> Option[B].

func MapOptionZ

func MapOptionZ[A, B any](o Option[A], f func(A) B) B

MapOptionZ transforms a pure function A -> B into one that will operate inside the Option context. Unlike MapOption, this function will return the default/zero argument of the return type if the Option is empty.

func MapRight

func MapRight[L, R, O any](f func(R) O) func(Either[L, R]) Either[L, O]

MapRight maps the right value of the Either to a new value.

func MapSecond

func MapSecond[A, B, C any](f func(A) B) func(T2[C, A]) T2[C, B]

MapSecond lifts the argument function into one that applies to the second element of a 2-tuple.

func Neq

func Neq[A comparable](x A) func(A) bool

Neq is a curried function that returns true if its eventual two arguments are not equal.

func NewSubMap

func NewSubMap[K comparable, V any](m map[K]V, keys []K) (map[K]V, error)

NewSubMap creates a sub-map from a given map using specified keys. It errors if any of the keys is not found in the map.

func NewSubMapIntersect

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

NewSubMapIntersect returns a sub-map of `m` containing only the keys found in both `m` and the `keys` slice.

func Pair

func Pair[A, B, C any](f func(A) B, g func(A) C) func(A) T2[B, C]

Pair takes two functions that share the same argument type and runs them both and produces a 2-tuple of the results.

func RecvOrTimeout

func RecvOrTimeout[T any](c <-chan T, timeout time.Duration) (T, error)

RecvOrTimeout attempts to recv over chan c, returning the value. If the timeout passes before the recv succeeds, an error is returned

func RecvResp

func RecvResp[T any](r <-chan T, e <-chan error, q <-chan struct{}) (T, error)

RecvResp takes three channels: a response channel, an error channel and a quit channel. If either of these channels are sent on, then the function will exit with that response. This can be used to wait for a response, error, or a quit signal.

func Replicate

func Replicate[A any](n uint, val A) []A

Replicate generates a slice of values initialized by the prototype value.

func SendOrQuit

func SendOrQuit[T any, Q any](c chan<- T, msg T, quit chan Q) bool

SendOrQuit attempts to and a message through channel c. If this succeeds, then bool is returned. Otherwise if a quit signal is received first, then false is returned.

func SetDiff

func SetDiff[T comparable](a, b []T) []T

SetDiff returns all the items that are in the first set but not in the second.

func SliceToMap

func SliceToMap[A any, K comparable, V any](s []A, keyFunc func(A) K,
	valueFunc func(A) V) map[K]V

SliceToMap converts a slice to a map using the provided key and value functions.

func Span

func Span[A any](s []A, pred Pred[A]) ([]A, []A)

Span, applied to a predicate and a slice, returns two slices where the first element is the longest prefix (possibly empty) of slice elements that satisfy the predicate and second element is the remainder of the slice.

func SplitAt

func SplitAt[A any](n uint, s []A) ([]A, []A)

SplitAt(n, s) returns a tuple where first element is s prefix of length n and second element is the remainder of the list.

func Sum

func Sum[B Number](items []B) B

Sum calculates the sum of a slice of numbers, `items`.

func TrimNones

func TrimNones[A any](as []Option[A]) []A

TrimNones takes a slice of Option values and returns a slice of the Some values in it.

func WriteFile added in v2.0.6

func WriteFile(name string, data []byte, perm os.FileMode) error

WriteFile synchronously writes data to the named file. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. By opening the file with O_SYNC, it ensures the data is written to disk. If an error occurs, it does not remove the file.

func WriteFileRemove added in v2.0.6

func WriteFileRemove(name string, data []byte, perm os.FileMode) error

WriteFileRemove synchronously writes data to the named file. If the file does not exist, WriteFileRemove creates it with permissions perm (before umask); otherwise WriteFileRemove truncates it before writing, without changing permissions. By opening the file with O_SYNC, it ensures the data is written to disk. If an error occurs, it removes the file.

func ZipWith

func ZipWith[A, B, C any](a []A, b []B, f func(A, B) C) []C

ZipWith combines slice elements with the same index using the function argument, returning a slice of the results.

Types

type ConcurrentQueue

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

ConcurrentQueue is a typed concurrent-safe FIFO queue with unbounded capacity. Clients interact with the queue by pushing items into the in channel and popping items from the out channel. There is a goroutine that manages moving items from the in channel to the out channel in the correct order that must be started by calling Start().

func NewConcurrentQueue

func NewConcurrentQueue[T any](bufferSize int) *ConcurrentQueue[T]

NewConcurrentQueue constructs a ConcurrentQueue. The bufferSize parameter is the capacity of the output channel. When the size of the queue is below this threshold, pushes do not incur the overhead of the less efficient overflow structure.

func (*ConcurrentQueue[T]) ChanIn

func (cq *ConcurrentQueue[T]) ChanIn() chan<- T

ChanIn returns a channel that can be used to push new items into the queue.

func (*ConcurrentQueue[T]) ChanOut

func (cq *ConcurrentQueue[T]) ChanOut() <-chan T

ChanOut returns a channel that can be used to pop items from the queue.

func (*ConcurrentQueue[T]) Start

func (cq *ConcurrentQueue[T]) Start()

Start begins a goroutine that manages moving items from the in channel to the out channel. The queue tries to move items directly to the out channel minimize overhead, but if the out channel is full it pushes items to an overflow queue. This must be called before using the queue.

func (*ConcurrentQueue[T]) Stop

func (cq *ConcurrentQueue[T]) Stop()

Stop ends the goroutine that moves items from the in channel to the out channel. This does not clear the queue state, so the queue can be restarted without dropping items.

type ContextGuard

type ContextGuard struct {
	// contains filtered or unexported fields
}

ContextGuard is a struct that provides a wait group and main quit channel that can be used to create guarded contexts.

func NewContextGuard

func NewContextGuard() *ContextGuard

NewContextGuard constructs and returns a new instance of ContextGuard.

func (*ContextGuard) Create added in v2.0.5

Create is used to derive a cancellable context from the parent. Various options can be provided to configure the behaviour of the derived context.

func (*ContextGuard) Done added in v2.0.5

func (g *ContextGuard) Done() <-chan struct{}

Done returns a channel that will be closed when the main quit signal is triggered.

func (*ContextGuard) Quit

func (g *ContextGuard) Quit()

Quit is used to signal the main quit channel, which will cancel all non-blocking contexts derived from the ContextGuard.

func (*ContextGuard) WgAdd added in v2.0.5

func (g *ContextGuard) WgAdd(delta int)

WgAdd is used to add delta to the internal wait group of the ContextGuard.

func (*ContextGuard) WgDone added in v2.0.5

func (g *ContextGuard) WgDone()

WgDone is used to decrement the internal wait group of the ContextGuard.

func (*ContextGuard) WgWait added in v2.0.5

func (g *ContextGuard) WgWait()

WgWait is used to block until the internal wait group of the ContextGuard is empty.

type ContextGuardOption added in v2.0.5

type ContextGuardOption func(*ctxGuardOptions)

ContextGuardOption defines the signature of a functional option that can be used to configure the behaviour of the context derived via the WithCtx method of the ContextGuard.

func WithBlockingCG added in v2.0.5

func WithBlockingCG() ContextGuardOption

WithBlockingCG is used to create a cancellable context that will NOT be cancelled if the main quit signal is triggered, to block shutdown of important tasks.

func WithCustomTimeoutCG added in v2.0.5

func WithCustomTimeoutCG(timeout time.Duration) ContextGuardOption

WithCustomTimeoutCG is used to create a cancellable context with a custom timeout. Such a context will be cancelled if either the parent context is cancelled, the timeout is reached or, if the Blocking option is not provided, the main quit signal is triggered.

func WithTimeoutCG added in v2.0.5

func WithTimeoutCG() ContextGuardOption

WithTimeoutCG is used to create a cancellable context with a default timeout. Such a context will be cancelled if either the parent context is cancelled, the timeout is reached or, if the Blocking option is not provided, the main quit signal is triggered.

type Copyable added in v2.0.3

type Copyable[T any] interface {
	Copy() T
}

Copyable is a generic interface for a type that's able to return a deep copy of itself.

type CopyableErr added in v2.0.3

type CopyableErr[T any] interface {
	Copy() (T, error)
}

CopyableErr is a generic interface for a type that's able to return a deep copy of itself. This is identical to Copyable, but should be used in cases where the copy method can return an error.

type Either

type Either[L any, R any] struct {
	// contains filtered or unexported fields
}

Either is a type that can be either left or right.

func NewLeft

func NewLeft[L any, R any](l L) Either[L, R]

NewLeft returns an Either with a left value.

func NewRight

func NewRight[L any, R any](r R) Either[L, R]

NewRight returns an Either with a right value.

func SomeToLeft

func SomeToLeft[O, R any](o Option[O], r R) Either[O, R]

SomeToLeft can be used to convert an Option value into an Either, by providing the Right value that should be used if the Option value is None.

func SomeToRight

func SomeToRight[O, L any](o Option[O], l L) Either[L, O]

SomeToRight can be used to convert an Option value into an Either, by providing the Left value that should be used if the Option value is None.

func (Either[L, R]) IsLeft

func (e Either[L, R]) IsLeft() bool

IsLeft returns true if the Either is left.

func (Either[L, R]) IsRight

func (e Either[L, R]) IsRight() bool

IsRight returns true if the Either is right.

func (Either[L, R]) LeftToSome

func (e Either[L, R]) LeftToSome() Option[L]

LeftToSome converts a Left value to an Option, returning None if the inner Either value is a Right value.

func (Either[L, R]) RightToSome

func (e Either[L, R]) RightToSome() Option[R]

RightToSome converts a Right value to an Option, returning None if the inner Either value is a Left value.

func (Either[L, R]) Swap

func (e Either[L, R]) Swap() Either[R, L]

Swap reverses the type argument order. This can be useful as an adapter between APIs.

func (Either[L, R]) UnwrapLeftOr

func (e Either[L, R]) UnwrapLeftOr(l L) L

UnwrapLeftOr will extract the Left value from the Either if it is present returning the supplied default if it is not.

func (Either[L, R]) UnwrapRightOr

func (e Either[L, R]) UnwrapRightOr(r R) R

UnwrapRightOr will extract the Right value from the Either if it is present returning the supplied default if it is not.

func (Either[L, R]) WhenLeft

func (e Either[L, R]) WhenLeft(f func(L))

WhenLeft executes the given function if the Either is left.

func (Either[L, R]) WhenRight

func (e Either[L, R]) WhenRight(f func(R))

WhenRight executes the given function if the Either is right.

type Event

type Event interface {
	Timestamp() time.Time
}

Event is a generic event that can be sent to a subscriber.

type EventDistributor

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

EventDistributor is a struct type that helps to distribute events to multiple subscribers.

func NewEventDistributor

func NewEventDistributor[T any]() *EventDistributor[T]

NewEventDistributor creates a new event distributor of the declared type.

func (*EventDistributor[T]) NotifySubscribers

func (d *EventDistributor[T]) NotifySubscribers(events ...T)

NotifySubscribers sends the given events to all subscribers.

func (*EventDistributor[T]) RegisterSubscriber

func (d *EventDistributor[T]) RegisterSubscriber(subscriber *EventReceiver[T])

RegisterSubscriber adds a new subscriber for receiving events.

func (*EventDistributor[T]) RemoveSubscriber

func (d *EventDistributor[T]) RemoveSubscriber(
	subscriber *EventReceiver[T]) error

RemoveSubscriber removes the given subscriber and also stops it from processing events.

type EventPublisher

type EventPublisher[T any, Q any] interface {
	// RegisterSubscriber adds a new subscriber for receiving events. The
	// deliverExisting boolean indicates whether already existing items
	// should be sent to the NewItemCreated channel when the subscription is
	// started. An optional deliverFrom can be specified to indicate from
	// which timestamp/index/marker onward existing items should be
	// delivered on startup. If deliverFrom is nil/zero/empty then all
	// existing items will be delivered.
	RegisterSubscriber(receiver *EventReceiver[T], deliverExisting bool,
		deliverFrom Q) error

	// RemoveSubscriber removes the given subscriber and also stops it from
	// processing events.
	RemoveSubscriber(subscriber *EventReceiver[T]) error
}

EventPublisher is an interface type for a component that offers event based subscriptions for publishing events.

type EventReceiver

type EventReceiver[T any] struct {

	// NewItemCreated is sent to when a new item was created successfully.
	NewItemCreated *ConcurrentQueue[T]

	// ItemRemoved is sent to when an existing item was removed.
	ItemRemoved *ConcurrentQueue[T]
	// contains filtered or unexported fields
}

EventReceiver is a struct type that holds two queues for new and removed items respectively.

func NewEventReceiver

func NewEventReceiver[T any](queueSize int) *EventReceiver[T]

NewEventReceiver creates a new event receiver with concurrent queues of the given size.

func (*EventReceiver[T]) ID

func (e *EventReceiver[T]) ID() uint64

ID returns the internal process-unique ID of the subscription.

func (*EventReceiver[T]) Stop

func (e *EventReceiver[T]) Stop()

Stop stops the receiver from processing events.

type GoroutineManager

type GoroutineManager struct {
	// contains filtered or unexported fields
}

GoroutineManager is used to launch goroutines until context expires or the manager is stopped. The Stop method blocks until all started goroutines stop.

func NewGoroutineManager

func NewGoroutineManager() *GoroutineManager

NewGoroutineManager constructs and returns a new instance of GoroutineManager.

func (*GoroutineManager) Done

func (g *GoroutineManager) Done() <-chan struct{}

Done returns a channel which is closed once Stop has been called and the quit channel closed. Note that the channel closing indicates that shutdown of the GoroutineManager has started but not necessarily that the Stop method has finished.

func (*GoroutineManager) Go

func (g *GoroutineManager) Go(ctx context.Context,
	f func(ctx context.Context)) bool

Go tries to start a new goroutine and returns a boolean indicating its success. It returns true if the goroutine was successfully created and false otherwise. A goroutine will fail to be created iff the goroutine manager is stopping or the passed context has already expired. The passed call-back function must exit if the passed context expires.

func (*GoroutineManager) Stop

func (g *GoroutineManager) Stop()

Stop prevents new goroutines from being added and waits for all running goroutines to finish.

type GuardConfig added in v2.0.5

type GuardConfig struct {
	// contains filtered or unexported fields
}

GuardConfig stores options for Guard function.

type GuardOption added in v2.0.5

type GuardOption func(*GuardConfig)

GuardOption is an option for Guard function.

func WithGuardTimeout added in v2.0.5

func WithGuardTimeout(timeout time.Duration) GuardOption

WithGuardTimeout sets timeout for the guard. Default is 5s.

type List

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

List represents a doubly linked list. The zero value for List is an empty list ready to use.

func NewList

func NewList[A any]() *List[A]

New returns an initialized List.

func (*List[A]) Back

func (l *List[A]) Back() *Node[A]

Back returns the last Node of List l or nil if the list is empty.

func (*List[A]) Filter

func (l *List[A]) Filter(f Pred[A]) []A

Filter gives a slice of all of the node values that satisfy the given predicate.

func (*List[A]) Front

func (l *List[A]) Front() *Node[A]

Front returns the first Node of List l or nil if the list is empty.

func (*List[A]) Init

func (l *List[A]) Init() *List[A]

Init intializes or clears the List l.

func (*List[A]) InsertAfter

func (l *List[A]) InsertAfter(a A, predecessor *Node[A]) *Node[A]

InsertAfter inserts a new Node n with value a immediately after and returns e. If predecessor is not an element of l, the list is not modified. The predecessor must not be nil.

func (*List[A]) InsertBefore

func (l *List[A]) InsertBefore(a A, successor *Node[A]) *Node[A]

InsertBefore inserts a new Node n with value a immediately before successor and returns n. If successor is not an element of l, the list is not modified. The successor must not be nil.

func (*List[A]) Len

func (l *List[A]) Len() int

Len returns the number of elements of List l. The complexity is O(1).

func (*List[A]) MoveAfter

func (l *List[A]) MoveAfter(n, predecessor *Node[A])

MoveAfter moves Node n to its new position after predecessor. If n or predecessor is not an element of l, or n == predecessor, the list is not modified. The Node and predecessor must not be nil.

func (*List[A]) MoveBefore

func (l *List[A]) MoveBefore(n, successor *Node[A])

MoveBefore moves Node n to its new position before successor. If n or successor is not an element of l, or n == successor, the list is not modified. The Node and successor must not be nil.

func (*List[A]) MoveToBack

func (l *List[A]) MoveToBack(n *Node[A])

MoveToBack moves Node n to the back of List l. If n is not an element of l, the list is not modified. The Node must not be nil.

func (*List[A]) MoveToFront

func (l *List[A]) MoveToFront(n *Node[A])

MoveToFront moves Node n to the front of List l. If n is not an element of l, the list is not modified. The Node must not be nil.

func (*List[A]) PushBack

func (l *List[A]) PushBack(a A) *Node[A]

PushBack inserts a new Node n with value a at the back of List l and returns n.

func (*List[A]) PushBackList

func (l *List[A]) PushBackList(other *List[A])

PushBackList inserts a copy of List other at the back of List l. The Lists l and other may be the same. They must not be nil.

func (*List[A]) PushFront

func (l *List[A]) PushFront(a A) *Node[A]

PushFront inserts a new Node n with value a at the front of List l and returns n.

func (*List[A]) PushFrontList

func (l *List[A]) PushFrontList(other *List[A])

PushFrontList inserts a copy of List other at the front of List l. The Lists l and other may be the same. They must not be nil.

func (*List[A]) Remove

func (l *List[A]) Remove(n *Node[A]) A

Remove removes Node n from List l if n is an element of List l. It returns the Node value e.Value. The Node must not be nil.

type Node

type Node[A any] struct {

	// Value is the actual data contained within the Node.
	Value A
	// contains filtered or unexported fields
}

func (*Node[A]) Next

func (e *Node[A]) Next() *Node[A]

Next returns the next list node or nil.

func (*Node[A]) Prev

func (e *Node[A]) Prev() *Node[A]

Prev returns the previous list node or nil.

type Number

type Number interface {
	constraints.Integer | constraints.Float | constraints.Complex
}

Number is a type constraint for all numeric types in Go (integers, float and complex numbers)

type Option

type Option[A any] struct {
	// contains filtered or unexported fields
}

Option represents a value which may or may not be there. This is very often preferable to nil-able pointers.

func CollectOptions

func CollectOptions[A any](options []Option[A]) Option[[]A]

CollectOptions collects a list of Options into a single Option of the list of Some values in it. If there are any Nones present it will return None.

func Find

func Find[A any](s []A, pred Pred[A]) Option[A]

Find returns the first value that passes the supplied predicate, or None if the value wasn't found.

func FindIdx

func FindIdx[A any](s []A, pred Pred[A]) Option[T2[int, A]]

FindIdx returns the first value that passes the supplied predicate along with its index in the slice. If no satisfactory value is found, None is returned.

func FlattenOption

func FlattenOption[A any](oo Option[Option[A]]) Option[A]

FlattenOption joins multiple layers of Options together such that if any of the layers is None, then the joined value is None. Otherwise the innermost Some value is returned.

FlattenOption : Option[Option[A]] -> Option[A].

func Head[A any](items []A) Option[A]

Head returns the first element of the slice, assuming it is non-empty.

func Init

func Init[A any](items []A) Option[[]A]

Init returns the slice without the last element, assuming the slice is not empty. Note this makes a copy of the slice.

func Last

func Last[A any](items []A) Option[A]

Last returns the last element of the slice, assuming it is non-empty.

func None

func None[A any]() Option[A]

None trivially constructs an empty option

None : Option[A].

func OptionFromPtr

func OptionFromPtr[A any](a *A) Option[A]

OptionFromPtr constructs an option from a pointer.

OptionFromPtr : *A -> Option[A].

func Some

func Some[A any](a A) Option[A]

Some trivially injects a value into an optional context.

Some : A -> Option[A].

func Tail

func Tail[A any](items []A) Option[[]A]

Tail returns the slice without the first element, assuming the slice is not empty. Note this makes a copy of the slice.

func TransposeResOpt

func TransposeResOpt[A any](r Result[Option[A]]) Option[Result[A]]

TransposeResOpt transposes the Result[Option[A]] into a Option[Result[A]]. This has the effect of leaving an A value alone while inverting the Result and Option layers. If there is no internal A value, it will convert the non-success value to the proper one in the transposition.

func TraverseOption

func TraverseOption[A, B any](as []A, f func(A) Option[B]) Option[[]B]

TraverseOption traverses a slice of A values, applying the provided function to each, collecting the results into an Option of a slice of B values. If any of the results are None, the entire result is None.

func Uncons

func Uncons[A any](items []A) Option[T2[A, []A]]

Uncons splits a slice into a pair of its Head and Tail.

func Unsnoc

func Unsnoc[A any](items []A) Option[T2[[]A, A]]

Unsnoc splits a slice into a pair of its Init and Last.

func (Option[A]) Alt

func (o Option[A]) Alt(o2 Option[A]) Option[A]

Alt chooses the left Option if it is full, otherwise it chooses the right option. This can be useful in a long chain if you want to choose between many different ways of producing the needed value.

Alt : Option[A] -> Option[A] -> Option[A].

func (Option[A]) IsNone

func (o Option[A]) IsNone() bool

IsNone returns true if the Option is empty

IsNone : Option[A] -> bool.

func (Option[A]) IsSome

func (o Option[A]) IsSome() bool

IsSome returns true if the Option contains a value

IsSome : Option[A] -> bool.

func (Option[A]) SomeToOk

func (o Option[A]) SomeToOk(err error) Result[A]

SomeToOk allows you to convert an Option value to a Result with your own error. If the Option contained a Some, then the supplied error is ignored and Some is converted to Ok.

func (Option[A]) SomeToOkf

func (o Option[A]) SomeToOkf(errString string, args ...interface{}) Result[A]

SomeToOkf allows you to convert an Option value to a Result with your own error message. If the Option contains a Some, then the supplied message is ignored and Some is converted to Ok.

func (Option[A]) UnsafeFromSome

func (o Option[A]) UnsafeFromSome() A

UnsafeFromSome can be used to extract the internal value. This will panic if the value is None() though.

func (Option[A]) UnwrapOr

func (o Option[A]) UnwrapOr(a A) A

UnwrapOr is used to extract a value from an option, and we supply the default value in the case when the Option is empty.

UnwrapOr : (Option[A], A) -> A.

func (Option[A]) UnwrapOrErr

func (o Option[A]) UnwrapOrErr(err error) (A, error)

UnwrapOrErr is used to extract a value from an option, if the option is empty, then the specified error is returned directly.

func (Option[A]) UnwrapOrFail

func (o Option[A]) UnwrapOrFail(t *testing.T) A

UnwrapOrFail is used to extract a value from an option within a test context. If the option is None, then the test fails.

func (Option[A]) UnwrapOrFunc

func (o Option[A]) UnwrapOrFunc(f func() A) A

UnwrapOrFunc is used to extract a value from an option, and we supply a thunk to be evaluated in the case when the Option is empty.

func (Option[A]) UnwrapOrFuncErr

func (o Option[A]) UnwrapOrFuncErr(f func() (A, error)) (A, error)

UnwrapOrFuncErr is used to extract a value from an option, and we supply a thunk to be evaluated in the case when the Option is empty.

func (Option[A]) WhenSome

func (o Option[A]) WhenSome(f func(A))

WhenSome is used to conditionally perform a side-effecting function that accepts a value of the type that parameterizes the option. If this function performs no side effects, WhenSome is useless.

WhenSome : (Option[A], A -> ()) -> ().

type Pred

type Pred[A any] func(A) bool

Pred[A] is a type alias for a predicate operating over type A.

func PredAnd

func PredAnd[A any](p0 Pred[A], p1 Pred[A]) Pred[A]

PredAnd is a lifted version of the && operation that operates over functions producing a boolean value from some type A.

func PredOr

func PredOr[A any](p0 Pred[A], p1 Pred[A]) Pred[A]

PredOr is a lifted version of the || operation that operates over functions producing a boolean value from some type A.

type Queue

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

Queue is a generic queue implementation.

func NewQueue

func NewQueue[T any](startingItems ...T) Queue[T]

NewQueue creates a new Queue.

func (*Queue[T]) Dequeue

func (q *Queue[T]) Dequeue() Option[T]

Dequeue removes an element from the front of the Queue. If there're no items in the queue, then None is returned.

func (*Queue[T]) Enqueue

func (q *Queue[T]) Enqueue(value ...T)

Enqueue adds one or more an items to the end of the Queue.

func (*Queue[T]) IsEmpty

func (q *Queue[T]) IsEmpty() bool

IsEmpty returns true if the Queue is empty

func (*Queue[T]) Peek

func (q *Queue[T]) Peek() Option[T]

Peek returns the first item in the queue without removing it. If the queue is empty, then None is returned.

func (*Queue[T]) Size

func (q *Queue[T]) Size() int

Size returns the number of items in the Queue

type Req

type Req[Input any, Output any] struct {
	// Request is the data we are sending to the remote goroutine for
	// processing.
	Request Input
	// contains filtered or unexported fields
}

Req is a type to encapsulate RPC-like calls wherein we send some data structure as a request, as well as a channel to receive the response on where the remote goroutine will send the result.

NOTE: This construct should only be used for request/response patterns for which there is only a single response for the request.

func NewReq

func NewReq[Input, Output any](input Input) (
	Req[Input, Output], <-chan Output)

NewReq is the base constructor of the Req type. It returns both the packaged Req object as well as the receive side of the response channel that we will listen on for the response.

func (*Req[Input, Output]) Dispatch

func (r *Req[Input, Output]) Dispatch(handler func(Input) Output)

Dispatch is a convenience method that lifts a function that transforms the Input to the Output type into a full request handling cycle.

func (*Req[Input, Output]) Resolve

func (r *Req[Input, Output]) Resolve(output Output)

Resolve is a function that is used to send a value of the Output type back to the requesting thread.

type Result

type Result[T any] struct {
	Either[T, error]
}

Result represents a value that can either be a success (T) or an error.

func AndThen

func AndThen[A, B any](r Result[A], f func(A) Result[B]) Result[B]

AndThen is an alias for FlatMap. This along with OrElse can be used to Railway Oriented Programming (ROP).

func CollectResults

func CollectResults[A any](results []Result[A]) Result[[]A]

CollectResults collects a list of Results into a single Result of the list of Ok values in it. If there are any errors present it will return the first error encountered.

func Err

func Err[T any](err error) Result[T]

Err creates a new Result with an error.

func Errf

func Errf[T any](errString string, args ...any) Result[T]

Errf creates a new Result with a new formatted error string.

func FlatMapResult

func FlatMapResult[A, B any](r Result[A], f func(A) Result[B]) Result[B]

FlatMapResult applies a function that returns a Result[B] to the success value if it exists.

func FlattenResult

func FlattenResult[A any](r Result[Result[A]]) Result[A]

FlattenResult takes a nested Result and joins the two functor layers into one.

func NewResult

func NewResult[T any](val T, err error) Result[T]

NewResult creates a new result from a (value, error) tuple.

func Ok

func Ok[T any](val T) Result[T]

Ok creates a new Result with a success value.

func TransposeOptRes

func TransposeOptRes[A any](o Option[Result[A]]) Result[Option[A]]

TransposeOptRes transposes the Option[Result[A]] into a Result[Option[A]]. This has the effect of leaving an A value alone while inverting the Option and Result layers. If there is no internal A value, it will convert the non-success value to the proper one in the transposition.

func TraverseResult

func TraverseResult[A, B any](as []A, f func(A) Result[B]) Result[[]B]

TraverseResult traverses a slice of A values, applying the provided function to each, collecting the results into a Result of a slice of B values. If any of the results are Err, the entire result is the first error encountered.

func (Result[T]) AndThen

func (r Result[T]) AndThen(f func(T) Result[T]) Result[T]

AndThen is an alias for FlatMap. This along with OrElse can be used to Railway Oriented Programming (ROP) by chaining successive computational operations from a single result type.

func (Result[T]) Err

func (r Result[T]) Err() error

Err exposes the underlying error of the result type as a normal error type.

func (Result[T]) FlatMap

func (r Result[T]) FlatMap(f func(T) Result[T]) Result[T]

FlatMap applies a kleisli endomorphic function that returns a Result to the success value if it exists.

func (Result[T]) IsErr

func (r Result[T]) IsErr() bool

IsErr returns true if the Result is an error.

func (Result[T]) IsOk

func (r Result[T]) IsOk() bool

IsOk returns true if the Result is a success value.

func (Result[T]) MapErr

func (r Result[T]) MapErr(f func(error) error) Result[T]

MapErr applies an endomorphic function to the error value if it exists.

func (Result[T]) MapOk

func (r Result[T]) MapOk(f func(T) T) Result[T]

MapOk applies an endomorphic function to the success value if it exists.

func (Result[T]) OkToSome

func (r Result[T]) OkToSome() Option[T]

OkToSome mutes the error value of the result.

func (Result[T]) OrElse

func (r Result[T]) OrElse(f func(error) Result[T]) Result[T]

OrElse returns the original Result if it is a success, otherwise it returns the provided alternative Result. This along with AndThen can be used to Railway Oriented Programming (ROP).

func (Result[A]) Sink

func (r Result[A]) Sink(f func(A) error) error

Sink consumes a Result, either propagating its error or processing its success value with a function that can fail.

func (Result[T]) Unpack

func (r Result[T]) Unpack() (T, error)

Unpack extracts the value or error from the Result.

func (Result[T]) UnwrapOr

func (r Result[T]) UnwrapOr(defaultValue T) T

UnwrapOr returns the success value or a default value if it's an error.

func (Result[T]) UnwrapOrElse

func (r Result[T]) UnwrapOrElse(f func(error) T) T

UnwrapOrElse returns the success value or computes a value from a function if it's an error.

func (Result[T]) UnwrapOrFail

func (r Result[T]) UnwrapOrFail(t *testing.T) T

UnwrapOrFail returns the success value or fails the test if it's an error.

func (Result[T]) WhenErr

func (r Result[T]) WhenErr(f func(error))

WhenErr executes the given function if the Result is an error.

func (Result[T]) WhenOk

func (r Result[T]) WhenOk(f func(T))

WhenOk executes the given function if the Result is a success.

type Set

type Set[T comparable] map[T]struct{}

Set is a generic set using type params that supports the following operations: diff, union, intersection, and subset.

func KeySet

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

KeySet converts a map into a Set containing the keys of the map.

func NewSet

func NewSet[T comparable](elems ...T) Set[T]

NewSet returns a new set with the given elements.

func (Set[T]) Add

func (s Set[T]) Add(e T)

Add adds an element to the set.

func (Set[T]) Contains

func (s Set[T]) Contains(e T) bool

Contains returns true if the set contains the element.

func (Set[T]) Copy added in v2.0.7

func (s Set[T]) Copy() Set[T]

Copy copies s and returns the result.

func (Set[T]) Diff

func (s Set[T]) Diff(other Set[T]) Set[T]

Diff returns the difference between two sets.

func (Set[T]) Equal

func (s Set[T]) Equal(other Set[T]) bool

Equal returns true if the set is equal to the other set.

func (Set[T]) Intersect

func (s Set[T]) Intersect(other Set[T]) Set[T]

Intersect returns the intersection of two sets.

func (Set[T]) IsEmpty

func (s Set[T]) IsEmpty() bool

IsEmpty returns true if the set is empty.

func (Set[T]) Remove

func (s Set[T]) Remove(e T)

Remove removes an element from the set.

func (Set[T]) Size

func (s Set[T]) Size() uint

Size returns the number of elements in the set.

func (Set[T]) Subset

func (s Set[T]) Subset(other Set[T]) bool

Subset returns true if the set is a subset of the other set.

func (Set[T]) ToSlice

func (s Set[T]) ToSlice() []T

ToSlice returns the set as a slice.

func (Set[T]) Union

func (s Set[T]) Union(other Set[T]) Set[T]

Union returns the union of two sets.

type T2

type T2[A, B any] struct {
	// contains filtered or unexported fields
}

T2 is the simplest 2-tuple type. It is useful for capturing ad hoc type conjunctions in a single value that can be easily dot-chained.

func NewT2

func NewT2[A, B any](a A, b B) T2[A, B]

NewT2 is the canonical constructor for a T2. We include it because the fields themselves are unexported.

func (T2[A, B]) First

func (t2 T2[A, B]) First() A

First returns the first value in the T2.

func (T2[A, B]) Second

func (t2 T2[A, B]) Second() B

Second returns the second value in the T2.

func (T2[A, B]) Unpack

func (t2 T2[A, B]) Unpack() (A, B)

Unpack ejects the 2-tuple's members into the multiple return values that are customary in go idiom.

type Unit

type Unit = struct{}

Unit is a type alias for the empty struct to make it a bit less noisy to communicate the informationaless type.

Jump to

Keyboard shortcuts

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