A Go package providing functional programming utilities built on Go's iter.Seq iterators. Uses a lisp-style free function API.
- Go 1.24+
go get github.com/eliothedeman/fn
Range(start, end)— produces a sequence of values fromstarttoend(exclusive) with a step of 1StepRange(start, end, step)— produces a sequence of values fromstarttoend(exclusive) with a custom stepChain(iters...)— concatenates multiple iterators into a single sequenceMap(iter, f)— transforms each element in an iterator using a functionFilter(iter, pred)— yields only elements that satisfy a predicateReduce(iter, seed, f)— folds an iterator into a single valueSum(iter)— sums all numeric values in an iterator
Both Result[T] and Option[T] satisfy Iterable[T] and work with the same set of unwrap functions:
Iter(x)— returns the iterator from anyIterable[T]HasValue(x)— returns true if the container holds a valueIsEmpty(x)— returns true if the container is empty (Err or None)Unwrap(x)— returns the value or panics if empty/errorUnwrapOr(x, def)— returns the value or a defaultUnwrapOrF(x, f)— returns the value or calls a function to produce a default
A generic Result[T] type for representing a value-or-error.
Ok(val)— creates a successful resultErr[T](err)— creates an error resultTry(val, err)— creates a result from a(T, error)pair, common with Go APIsUnpack(r)— returns the(T, error)pairIterErr(r)— yields the error if Err, nothing if Ok
A generic Option[T] type for representing an optional value.
Some(val)— creates an Option containing a valueNone[T]()— creates an empty Option
package main
import (
"fmt"
"github.com/eliothedeman/fn"
)
func main() {
// Sum integers 0..99
total := fn.Sum(fn.Range(0, 100))
fmt.Println(total) // 4950
// Map and filter
evens := fn.Filter(fn.Range(0, 20), func(i int) bool {
return i%2 == 0
})
doubled := fn.Map(evens, func(i int) int {
return i * 2
})
fmt.Println(fn.Sum(doubled)) // 180
// Result type
r := fn.Ok(42)
val, err := fn.Unpack(r)
fmt.Println(val, err) // 42 <nil>
// Option type
o := fn.Some("hello")
fmt.Println(fn.UnwrapOr(o, "default")) // hello
fmt.Println(fn.UnwrapOr(fn.None[string](), "default")) // default
}MIT