Skip to content

Commit

Permalink
initial checkin
Browse files Browse the repository at this point in the history
Signed-off-by: Dr. Carsten Leue <[email protected]>
  • Loading branch information
CarstenLeue committed Jul 7, 2023
1 parent 71c47ca commit c07df5c
Show file tree
Hide file tree
Showing 128 changed files with 5,827 additions and 2 deletions.
126 changes: 124 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,124 @@
# fp-go
functional programming library for golang
# Functional programming library for golang

![logo](resources/images/logo.png)

## Design Goal

This library aims to provide a set of data types and functions that make it easy and fun to write maintainable and testable code in golang. It encourages the following patterns:

- write many small, testable and pure functions, i.e. functions that produce output only depending on their input and that do not execute side effects
- offer helpers to isolate side effects into lazily executed functions (IO)
- expose a consistent set of composition to create new functions from existing ones
- for each data type there exists a small set of composition functions
- these functions are called the same across all data types, so you only have to learn a small number of function names
- the semantic of functions of the same name is consistent across all data types

### How does this play with the [🧘🏽 Zen Of Go](https://the-zen-of-go.netlify.app/)?

#### 🧘🏽 Each package fulfils a single purpose

✔️ Each of the top level packages (e.g. Option, Either, Task, ...) fulfils the purpose of defining the respective data type and implementing the set of common operations for this data type.

#### 🧘🏽 Handle errors explicitly

✔️ The library makes a clear distinction between that operations that cannot fail by design and operations that can fail. Failure is represented via the `Either` type and errors are handled explicitly by using `Either`'s monadic set of operations.

#### 🧘🏽 Return early rather than nesting deeply

✔️ We recommend to implement simple, small functions that implement one feature and that would typically not invoke other functions. Interaction with other functions is done by function composition and the composition makes sure to run one function after the other. In the error case the `Either` monad makes sure to skip the error path.

#### 🧘🏽 Leave concurrency to the caller

✔️ All operations are synchronous by default, including `Task`. Concurrency must be coded by the consumer of these functions explicitly, but the implementation is ready to deal with concurrent usage.

#### 🧘🏽 Before you launch a goroutine, know when it will stop

🤷🏽 This is left to the user of the library since the library itself will not start goroutines on its own. The Task monad offers support for cancellation via the golang context, though.

#### 🧘🏽 Avoid package level state

✔️ No package level state anywhere, this would be a significant anti-pattern

#### 🧘🏽 Simplicity matters

✔️ The library is simple in the sense that it offers a small, consistent interface to a variety of data types. Users can concentrate on implementing business logic rather than dealing with low level data structures.

#### 🧘🏽 Write tests to lock in the behaviour of your package’s API

🟡 The programming pattern suggested by this library encourages writing test cases. The library itself also has a growing number of tests, but not enough, yet. TBD

#### 🧘🏽 If you think it’s slow, first prove it with a benchmark

✔️ Absolutely. If you think the function composition offered by this library is too slow, please provide a benchmark.

#### 🧘🏽 Moderation is a virtue

✔️ The library does not implement its own goroutines and also does not require any expensive synchronization primitives. Coordination of Tasks is implemented via atomic counters without additional primitives. Channels are only used in the `Wait` function of a Task that should be invoked at most once in a complete application.

#### 🧘🏽 Maintainability counts

✔️ Code that consumes this library is easy to maintain because of the small and concise set of operations exposed. Also the suggested programming paradigm to decompose an application into small functions increases maintainability, because these functions are easy to understand and if they are pure, it's often sufficient to look at the type signature to understand the purpose.

The library itself also comprises many small functions, but it's admittedly harder to maintain than code that uses it. However this asymmetry is intended because it offloads complexity from users into a central component.

## Implementation Notes

### Generics

All monadic operations are implemented via generics, i.e. they offer a type safe way to compose operations. This allows for convenient IDE support and also gives confidence about the correctness of the composition at compile time.

Downside is that this will result in different versions of each operation per type, these versions are generated by the golang compiler at build time (unlike type erasure in languages such as Java of TypeScript). This might lead to large binaries for codebases with many different types. If this is a concern, you can always implement type erasure on top, i.e. use the monadic operations with the `any` type as if generics were not supported. You loose type safety, but this might result in smaller binaries.

### Use of the [~ Operator](https://go.googlesource.com/proposal/+/master/design/47781-parameterized-go-ast.md)

The FP library attempts to be easy to consume and one aspect of this is the definition of higher level type definitions instead of having to use their low level equivalent. It is e.g. more convenient and readable to use

```go
TaskEither[E, A]
```

than

```go
func(func(Either.Either[E, A]))
```

although both are logically equivalent. At the time of this writing the go type system does not support generic type aliases, only generic type definition, i.e. it is not possible to write:

```go
type TaskEither[E, A any] = T.Task[ET.Either[E, A]]
```

only

```go
type TaskEither[E, A any] T.Task[ET.Either[E, A]]
```

This makes a big difference, because in the second case the type `TaskEither[E, A any]` is considered a completely new type, not compatible to its right hand side, so it's not just a shortcut but a fully new type.

From the implementation perspective however there is no reason to restrict the implementation to the new type, it can be generic for all compatible types. The way to express this in go is the [~](https://go.googlesource.com/proposal/+/master/design/47781-parameterized-go-ast.md) operator. This comes with some quite complicated type declarations in some cases, which undermines the goal of the library to be easy to use.

For that reason there exist sub-packages called `Generic` for all higher level types. These packages contain the fully generic implementation of the operations, preferring abstraction over usability. These packages are not meant to be used by end-users but are meant to be used by library extensions. The implementation for the convenient higher level types specializes the generic implementation for the particular higher level type, i.e. this layer does not contain any business logic but only *type magic*.

### Higher Kinded Types

Go does not support higher kinded types (HKT). Such types occur if a generic type itself is parametrized by another generic type. Example:

The `Map` operation for `Task` is defined as:

```go
func Map[A, B any](f func(A) B) func(Task[A]) Task[B]
```

and in fact the equivalent operations for all other mondas follow the same pattern, we could try to introduce a new type for `Task` (without a parameter) as a HKT, e.g. like so (made-up syntax, does not work in go):

```go
func Map[HKT, A, B any](f func(A) B) func(HKT[A]) HKT[B]
```

this would be the completely generic method signature for all possible monads. In particular in many cases it is possible to compose functions independent of the concrete knowledge of the actual `HKT`. From the perspective of a library this is the ideal situation because then a particular algorithm only has to be implemented and tested once.

This FP library addresses this by introducing the HKTs as individual types, e.g. `HKT[A]` would be represented as a new generic type `HKTA`. This loses the correlation to the type `A` but allows to implement generic algorithms, at the price of readability.

For that reason these implementations are kept in the `internal` package. These are meant to be used by the library itself or by extensions, not by end users.
72 changes: 72 additions & 0 deletions apply/sequence.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package Apply

import (
F "github.com/ibm/fp-go/function"
T "github.com/ibm/fp-go/tuple"
)

func tupleConstructor1[A any]() func(A) T.Tuple1[A] {
return F.Curry1(T.MakeTuple1[A])
}

func tupleConstructor2[A, B any]() func(A) func(B) T.Tuple2[A, B] {
return F.Curry2(T.MakeTuple2[A, B])
}

func tupleConstructor3[A, B, C any]() func(A) func(B) func(C) T.Tuple3[A, B, C] {
return F.Curry3(T.MakeTuple3[A, B, C])
}

func tupleConstructor4[A, B, C, D any]() func(A) func(B) func(C) func(D) T.Tuple4[A, B, C, D] {
return F.Curry4(T.MakeTuple4[A, B, C, D])
}

func SequenceT1[A, HKTA, HKT1A any](
fmap func(HKTA, func(A) T.Tuple1[A]) HKT1A,
a HKTA) HKT1A {
return fmap(a, tupleConstructor1[A]())
}

// HKTA = HKT[A]
// HKTB = HKT[B]
// HKT2AB = HKT[Tuple[A, B]]
// HKTFB2AB = HKT[func(B)Tuple[A, B]]
func SequenceT2[A, B, HKTA, HKTB, HKTFB2AB, HKT2AB any](
fmap func(HKTA, func(A) func(B) T.Tuple2[A, B]) HKTFB2AB,
fap1 func(HKTFB2AB, HKTB) HKT2AB,
a HKTA, b HKTB,
) HKT2AB {
return fap1(fmap(a, tupleConstructor2[A, B]()), b)
}

// HKTA = HKT[A]
// HKTB = HKT[B]
// HKTC = HKT[C]
// HKT3ABC = HKT[Tuple[A, B, C]]
// HKTFB3ABC = HKT[func(B)func(C)Tuple[A, B, C]]
// HKTFC3ABC = HKT[func(C)Tuple[A, B, C]]
func SequenceT3[A, B, C, HKTA, HKTB, HKTC, HKTFB3ABC, HKTFC3ABC, HKT3ABC any](
fmap func(HKTA, func(A) func(B) func(C) T.Tuple3[A, B, C]) HKTFB3ABC,
fap1 func(HKTFB3ABC, HKTB) HKTFC3ABC,
fap2 func(HKTFC3ABC, HKTC) HKT3ABC,

a HKTA, b HKTB, c HKTC) HKT3ABC {
return fap2(fap1(fmap(a, tupleConstructor3[A, B, C]()), b), c)
}

// HKTA = HKT[A]
// HKTB = HKT[B]
// HKTC = HKT[C]
// HKT3ABCD = HKT[Tuple[A, B, C, D]]
// HKTFB3ABCD = HKT[func(B)func(C)func(D)Tuple[A, B, C, D]]
// HKTFC3ABCD = HKT[func(C)func(D)Tuple[A, B, C, D]]
// HKTFD3ABCD = HKT[func(D)Tuple[A, B, C, D]]
func SequenceT4[A, B, C, D, HKTA, HKTB, HKTC, HKTD, HKTFB4ABCD, HKTFC4ABCD, HKTFD4ABCD, HKT4ABCD any](
fmap func(HKTA, func(A) func(B) func(C) func(D) T.Tuple4[A, B, C, D]) HKTFB4ABCD,
fap1 func(HKTFB4ABCD, HKTB) HKTFC4ABCD,
fap2 func(HKTFC4ABCD, HKTC) HKTFD4ABCD,
fap3 func(HKTFD4ABCD, HKTD) HKT4ABCD,

a HKTA, b HKTB, c HKTC, d HKTD) HKT4ABCD {
return fap3(fap2(fap1(fmap(a, tupleConstructor4[A, B, C, D]()), b), c), d)
}
Loading

0 comments on commit c07df5c

Please sign in to comment.