maybe

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2022 License: MIT Imports: 1 Imported by: 0

README

Go Reference Go Report Card

Maybe

Maybe provides an implementation of the maybe type.


Documentation

Overview

Package maybe provides a container type and utilities for optional values.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Value

func Value[A, B any](dflt B, f func(a A) B, v An[A]) B

Value returns the default value `dflt` if `v` is Nothing. Otherwise it returns the result of calling `f` on `v`.

Example
package main

import (
	"fmt"

	"github.com/calebcase/maybe"
)

func main() {
	// Odd returns true if the integer is odd.
	odd := func(v int) bool {
		return v%2 != 0
	}

	// NOTE: The additional type hinting `maybe.An[int](...)` is currently
	// necessary because of a limitation in Go's type inferencing. The
	// hinting may eventually be unnecessary when/if the type inferencing
	// improves for generics.
	fmt.Println(maybe.Value(false, odd, maybe.An[int](maybe.Just[int]{3})))
	fmt.Println(maybe.Value(false, odd, maybe.An[int](maybe.Nothing[int]{})))

	// These all produce the desired compile time error (because the types
	// are mismatched):
	//
	//fmt.Println(maybe.Value(false, odd, maybe.An[float32](maybe.Nothing[int]{})))
	//fmt.Println(maybe.Value(false, odd, maybe.An[float32](maybe.Nothing[float32]{})))
	//fmt.Println(maybe.Value(false, odd, maybe.An[int](maybe.Just[float32]{3})))

	// str returns the string even or odd for the value.
	str := func(v int) string {
		if v%2 == 0 {
			return "even"
		}

		return "odd"
	}

	fmt.Println(maybe.Value("unknown", str, maybe.An[int](maybe.Just[int]{3})))
	fmt.Println(maybe.Value("unknown", str, maybe.An[int](maybe.Just[int]{4})))
	fmt.Println(maybe.Value("unknown", str, maybe.An[int](maybe.Nothing[int]{})))

}
Output:

true
false
odd
even
unknown

Types

type An

type An[T any] interface {
	// contains filtered or unexported methods
}

type Just

type Just[T any] struct {
	Value T
}

Just contains a value.

type Nothing

type Nothing[T any] struct{}

Nothing indicates no value is present.

Jump to

Keyboard shortcuts

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