Skip to content

go-functional is a library that offers functional programming in Go using generics

License

Notifications You must be signed in to change notification settings

myusko/go-functional

 
 

Repository files navigation

Functional Programming in Go

GitHub release (with filter) Actions Status Go Reference Go Report Card codecov

A general purpose library offering functional helpers for Golang.

// Find the first 5 even numbers
evens := iter.Count().Filter(filters.IsEven).Take(5).Collect()
reflect.DeepEqual(evens, []int{0, 2, 4, 6, 8})

Read the docs.

Core concepts

This library introduces two core concepts, the Iterator and the Option. Using these two concepts this library derives many pre-defined iterators for use.

The Option

The Option is simply a type that represents the presence or absence of a value. Options behave somewhat like enumerations with two variants: Some(value) and None.

The Iterator

type Iterator[T any] interface {
	Next() option.Option[T]
}

The Iterator is an interface that defines the behaviour of some type that "yields" values. Each call to Next() on an Iterator will yield another value as defined by that specific Iterator. For example, the iterator iter.Count() yields 0, 1, 2, 3, etc. and onwards to infinity (or the integer limit!).

Iterators will yield Some(value) for as long as they have values to yield. Iterators that have exhausted all their values will then always yield None.

This library defines many iterators and a few are demonstrated below. For the entire set simply visit the package documentation.

Iterator showcase

Here are a few trivial example of what's possible using the iterators in this library.

// All odd natural numbers (1, 3, 5, 7...)
odds := iter.Count().Drop(1).Filter(filters.IsOdd).Collect()
// All lines from a file
lines := iter.LinesString(file).CollectResults().Unwrap()
// String representations of numbers
numbers := iter.Map(iter.Count(), strconv.Itoa)

About

go-functional is a library that offers functional programming in Go using generics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 99.7%
  • Makefile 0.3%