Functional programming in Go (fp-go)

repeale

Alessio Enrico Repetti

Posted on April 19, 2022

Functional programming in Go (fp-go)

From the beginning when golang was released i always faced couple of missing bits:

  • Generics
  • Functional programming

Then golang v1.18 came out with generics.
This suddenly unlocked a lot of new ways of writing code in golang.
In detail now it's possible to easily write generic functions that help you to write code in a more functional way.

For this purpose i started an open source project that aims to fill this remaining gap of the language.

GitHub logo repeale / fp-go

fp-go is a collection of Functional Programming helpers powered by Golang 1.18+ generics.

fp-go

Go Reference Go Report codecov

Fp-go is a collection of Functional Programming helpers powered by Golang 1.18+ generics.

Inspired by

Contents

Install

Requires go 1.18+

go get github.com/repeale/fp-go
Enter fullscreen mode Exit fullscreen mode

Features

Currying

By default! Data last!

func isPositive(x int) bool {
    return x > 0
}

func main() {
    filterPositive := fp.Filter(isPositive)
    numbers := []int{1, 2, 3, 4, 5}

    positives := filterPositive(numbers)
}
Enter fullscreen mode Exit fullscreen mode

Variations

Variations allows you to get different parameters in the callback function so that you get only only what is really needed.

Default
WithIndex
WithSlice

Default

Only the current item is available:

fp.Map[int, string](func(x int) { ... })
Enter fullscreen mode Exit fullscreen mode

WithIndex

Current…

The project is already in a good shape that allows you to write good functional code. But it's still under development and i'm looking for help to expand the collection of helpers.

Here you could find the list of Helpers with examples.

Couple of core pillars of the library:

Currying

By default, data are always at last. This allow to write upfront reusable code that can run with the actual data only when needed.

// Example with Map helper

func int64toInt(x int64) string {
    return strconv.FormatInt(x, 10)
}

// ...

data := []int64{1, 2, 3}

fp.Map(int64toInt)(data)

// => []string{"1", "2", "3", "4"}
Enter fullscreen mode Exit fullscreen mode

Variations

Each helper come with variations. This allow you to use the right implementation for your use case without having to deal with unused code. The full doc could be found here .

// Available variations

// Default
fp.Map[int, string](func(x int) { ... })

// *WithIndex
fp.MapWithIndex[int, string](func(x int, i int) { ... })

// *WithSlice
fp.MapWithSlice[int, string](func(x int, i int, xs: []int) { ... })
Enter fullscreen mode Exit fullscreen mode

Looking forward for contributors, feedbacks and more new features to come i really hope you will enjoy using this package!

💖 💪 🙅 🚩
repeale
Alessio Enrico Repetti

Posted on April 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related