gonads

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: MIT Imports: 4 Imported by: 0

README

gonads

Go Reference Go Version

[!INFO] This library uses Go 1.27rc1 for generic methods, which is not a stable release

A minimal library for monadic types and functional list abstractions, leveraging Go 1.27 generics.

Design:

  • Small footprint, favoring composable types and methods
  • "Dot import" friendly, only provides constructors and a few utilities in the namespace
  • Chainable methods provide type operations

Features

All types have safe accessors, and map/filter/fold methods.

  • Option[T] - Some/None type
    • Some: Value is present and accessible
    • None: no value, must be handled
  • Result[T] - Ok/Error type
    • Ok: Value is present and accessible
    • Err: Error encountered, must be handled
  • List[T] - Slice with functional helpers

Quick Start

foo := PackResult(ThingThatCanError()).
    Map(func(x int) int { return x * 2 }).
    Fold(
        func(x int) string { return fmt.Sprintf("Value: %v", x) },
        func(e error) string { return fmt.Sprintf("Uh Oh... [%v]", e) },
    )

fmt.Println(foo)
func isEven(x int) bool {
	return x%2 == 0
}

func main() {
	evens := List[int]{1, 2, 3, 4, 5, 6, 7}.Filter(isEven)

	first := evens.First()
	count := len(evens)
	avg := evens.Reduce(func(a int, b int) int { return a + b }, 0) / count

	if first.IsSome() {
		fmt.Printf("First Even: %v\n", first.Get())
		fmt.Printf("Num Evens: %v\n", count)
		fmt.Printf("Avg of evens: %v\n", avg)
	} else {
		fmt.Printf("No evens...")
	}
}
Installation

go get github.com/FreeSamples00/gonads

Importing

Dot Import

Recommended for top level Ok() style constructors.

import (
    . "github.com/FreeSamples00/gonads"
)

Import

import "github.com/FreeSamples00/gonads"

API Reference

Full documentation is available here.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrIsOk = errors.New("Result: no error")

Simple error for Result

View Source
var ErrNone = errors.New("Option: no value")

Simple error for Option

Functions

This section is empty.

Types

type List

type List[T any] []T

List holds an ordered sequence of elements.

func New

func New[T any](capacity int) List[T]

New creates an empty List with the specified capacity.

Returns List[T] with length 0 and the given capacity.

func PackList

func PackList[T any](s []T) List[T]

PackList wraps an existing slice as a List.

Creates List[T] sharing the backing array of s. Mutations to the returned List affect s and vice versa. Use Clone for an independent copy.

func (List[T]) Append

func (l List[T]) Append(v ...T) List[T]

Append adds elements to the end of the List.

Returns a new List[T] with v appended.

func (List[T]) At

func (l List[T]) At(i int) Option[T]

At returns an Option containing the element at index i.

In bounds: Creates Some(l[i]). Out of bounds: Creates None.

func (List[T]) Clone

func (l List[T]) Clone() List[T]

Clone returns a copy of the List.

Creates a new List with a fresh backing array.

func (List[T]) Delete

func (l List[T]) Delete(i, j int) List[T]

Delete removes elements from index i to j.

Returns a new List[T] with elements l[i:j] removed.

func (List[T]) Filter

func (l List[T]) Filter(fn func(T) bool) List[T]

Filter returns a new List containing only elements matching fn.

fn returns true: Element is included. fn returns false: Element is excluded.

func (List[T]) Find

func (l List[T]) Find(fn func(T) bool) Option[T]

Find returns an Option containing the first element matching fn.

Match found: Creates Some(l[i]). No match: Creates None.

func (List[T]) First

func (l List[T]) First() Option[T]

First returns an Option containing the first element.

Non-empty: Creates Some(l[0]). Empty: Creates None.

func (List[T]) Insert

func (l List[T]) Insert(i int, v ...T) List[T]

Insert inserts values at index i.

Returns a new List[T] with v inserted at position i.

func (List[T]) Last

func (l List[T]) Last() Option[T]

Last returns an Option containing the last element.

Non-empty: Creates Some(l[len(l)-1]). Empty: Creates None.

func (List[T]) Map

func (l List[T]) Map[U any](fn func(T) U) List[U]

Map applies fn to each element, returning a new List of the results.

Returns List[U] where each element is fn(original).

func (List[T]) Max

func (l List[T]) Max(less func(a, b T) bool) Option[T]

Max returns the maximum element according to less.

Non-empty: Returns Some(max). Empty: Returns None.

func (List[T]) Min

func (l List[T]) Min(less func(a, b T) bool) Option[T]

Min returns the minimum element according to less.

Non-empty: Returns Some(min). Empty: Returns None.

func (List[T]) Reduce

func (l List[T]) Reduce[U any](fn func(U, T) U, init U) U

Reduce folds all elements into a single value using fn.

Returns the accumulated result starting from init.

func (List[T]) Reverse

func (l List[T]) Reverse() List[T]

Reverse reverses the List in place.

Returns l with element order reversed.

func (List[T]) Sort

func (l List[T]) Sort(less func(a, b T) bool) List[T]

Sort sorts the List using the comparator less.

less(a, b) returns true if a should come before b. Returns l sorted in place.

func (List[T]) Unpack

func (l List[T]) Unpack() []T

Unpack returns the List as a plain slice.

Returns []T sharing the backing array of l.

type Option

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

Option holds either a value or represents a null value.

func CollectOption

func CollectOption[T any](s []Option[T]) Option[[]T]

CollectOption converts a slice of Options into an Option of slice.

All Some: Creates Some containing all values. Any None: Creates None.

func None

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

None creates an Option with no value.

Creates Option[T] with no value. Type must be specified.

func PackOption

func PackOption[T any](v T, ok bool) Option[T]

PackOption converts a Go (v, ok) return pair into an Option. The inverse of Unpack.

ok == true: Creates Option[T] with value. ok == false: Creates Option[T] with no value.

func Some

func Some[T any](value T) Option[T]

Some wraps a value in an Option.

Creates Option[T] with value. Type is inferred from the argument.

func (Option[T]) Alt

func (o Option[T]) Alt(fn func() Option[T]) Option[T]

Alt replaces none with result of fn.

targets None. Some: propagated forward. None: returns fn().

func (Option[T]) Filter

func (o Option[T]) Filter(fn func(T) bool) Option[T]

Filter keeps the value only if fn returns true.

targets Some. Some and fn(val) is true: returns the original Option. Some and fn(val) is false: returns None. None: propagated forward.

func (Option[T]) Fold

func (o Option[T]) Fold[O any](somefn func(T) O, nonefn func() O) O

Fold collapses the Option into a single value.

Some: somefn(val). None: nonefn().

func (Option[T]) Get

func (o Option[T]) Get() T

Get returns the contained value.

targets Some. Some: returns the contained value. None: panics with ErrNone.

func (Option[T]) IsNone

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

IsNone reports whether the Option is missing a value.

targets None. Some: returns false. None: returns true.

func (Option[T]) IsSome

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

IsSome reports whether the Option holds a value.

targets Some. Some: returns true. None: returns false.

func (Option[T]) Map

func (o Option[T]) Map[O any](fn func(T) O) Option[O]

Map applies fn to the contained value, wrapping the result in Some.

targets Some. Some: Some(fn(val)). None: propagated forward.

func (Option[T]) MapFlat

func (o Option[T]) MapFlat[O any](fn func(T) Option[O]) Option[O]

MapFlat applies fn to the contained value and returns the resulting Option.

targets Some. Some: returns fn(val). None: propagated forward.

func (Option[T]) Match

func (o Option[T]) Match(somefn func(T), nonefn func())

Match dispatches to one of two side-effect functions.

Some: somefn(val). None: nonefn().

func (Option[T]) Or

func (o Option[T]) Or(fallback T) T

Or returns the contained value.

targets Some. Some: returns the contained value. None: returns fallback.

func (Option[T]) OrElse

func (o Option[T]) OrElse(fn func() T) T

OrElse returns the contained value.

targets Some. Some: returns the contained value. None: calls fn, returns its result.

func (Option[T]) Unpack

func (o Option[T]) Unpack() (v T, ok bool)

Unpack returns the Option as a Go (v, ok) pair. The inverse of PackOption.

Some: (val, true). None: (zero, false).

type PanicError

type PanicError struct {
	Value any    // value passed to panic
	Stack string // captured stack trace
}

PanicError wraps a value recovered from panic.

func (*PanicError) Error

func (e *PanicError) Error() string

Error returns the message of the caught panic.

Value is error: returns its Error string. Otherwise: returns fmt.Sprintf("%v", Value).

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

Unwrap returns the underlying error.

Value is error: returns Value. Otherwise: returns nil.

type Result

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

Result holds either a value of type T or an error.

func CollectResult

func CollectResult[T any](s []Result[T]) Result[[]T]

CollectResult converts a slice of Results into a Result of slice.

All Ok: Creates Ok containing all values. Any Err: Creates Err of the first error.

func Err

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

Err wraps an error in a Result.

Creates Result[T] with error. Type must be specified.

func Ok

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

Ok wraps a value in a Result.

Creates Result[T] with value. Type is inferred from the argument.

func PackResult

func PackResult[T any](value T, err error) Result[T]

PackResult converts a Go (v, error) return pair into a Result. The inverse of Unpack.

err == nil: Creates Result[T] with value. err != nil: Creates Result[T] with error.

func Try

func Try[T any](fn func() T) (result Result[T])

Try calls fn and wraps the result in a Result.

fn returns: Creates Ok(val). fn panics: Creates Err(*PanicError) with the panic value and stack trace.

func (Result[T]) Catch

func (r Result[T]) Catch(fn func(error) Result[T]) Result[T]

Catch applies fn to the contained error to produce an alternative Result. Can recover from the error.

targets Err. Ok: no-op. Err: returns fn(err).

func (Result[T]) Fold

func (r Result[T]) Fold[O any](okfn func(T) O, errfn func(error) O) O

Fold collapses the Result into a single value.

Ok: okfn(val). Err: errfn(err).

func (Result[T]) Get

func (r Result[T]) Get() T

Get returns the contained value.

targets Ok. Ok: returns the contained value. Err: panics with stored error.

func (Result[T]) GetErr

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

GetErr returns the contained error.

targets Err. Ok: panics with ErrIsOk. Err: returns the contained error.

func (Result[T]) IsErr

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

IsErr reports whether the Result contains an error.

targets Err. Ok: returns false. Err: returns true.

func (Result[T]) IsOk

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

IsOk reports whether the Result contains a value.

targets Ok. Ok: returns true. Err: returns false.

func (Result[T]) Map

func (r Result[T]) Map[O any](fn func(T) O) Result[O]

Map applies fn to the contained value, wrapping the result in Ok.

targets Ok. Ok: Ok(fn(val)). Err: propagated forward.

func (Result[T]) MapErr

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

MapErr replaces the contained error.

targets Err. Ok: no-op. Err: Err(fn(err)).

func (Result[T]) MapFlat

func (r Result[T]) MapFlat[O any](fn func(T) Result[O]) Result[O]

MapFlat applies fn to the contained value and returns the resulting Result.

targets Ok. Ok: returns fn(val). Err: propagated forward.

func (Result[T]) Match

func (r Result[T]) Match(okfn func(T), errfn func(error))

Match dispatches to one of two side-effect functions.

Ok: okfn(val). Err: errfn(err).

func (Result[T]) Or

func (r Result[T]) Or(fallback T) T

Or returns the contained value.

targets Ok. Ok: returns the contained value. Err: returns fallback.

func (Result[T]) OrElse

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

OrElse returns the contained value.

targets Ok. Ok: returns the contained value. Err: calls fn with error, returns its result.

func (Result[T]) Unpack

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

Unpack returns the Result as a Go (v, error) pair. The inverse of PackResult.

Ok: (val, nil). Err: (val, err).

Jump to

Keyboard shortcuts

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