The shape of a functor
A functor is an algebraic type that accepts a value (or usually, a list of values) and has a map function that applies to each element in the list to produce a new functor of the same shape. What is a shape?
Let's look at an imperative example:
ints := []int{1,2,3} impInts := []int{} for _, v := range ints { impInts = append(impInts, v + 2) } fmt.Println("imperative loop:", impInts)
Here's the output:
imperative loop: [3 4 5]
The shape in this example means a slice with three ints. We started with a slice with three ints, ran our imperative code, and ended up with a slice with three ints.
A functor gets the same results (three elements in and three elements out) but a functor does it in a different way.
We give our functor the same slice of three ints. The functor executes add2
for each int and returns a slice with three ints (each of which is two greater than before):
add2 := func(i int) int { return i + 2 } fpInts := Functor(ints).Map(add2) fmt.Println("fp map:", fpInts...