Functors

A functor is a functional programming paradigm in which a transformation is performed on a structure while the structure is preserved.

In our example, we take an integer slice, intSlice, and lift the slice into a functor. IntSliceFunctor is an interface that includes the following:

  • fmt.Stringer, which defines the string format for the value with its representation.
  • Map(fn func(int int) IntSliceFunctor â€“ this mapping applies fn to each element in our slice.
  • A convenience function, Ints() []int, which allows you to get the int slice the functor holds.

After we have our lifted slice, we can perform operations on our newly created functor. In our example, we perform a square operation and a modulus three operation. The following is an example implementation of a functor:

package main                                                                                                                                

import (
"fmt"

"github.com/go-functional/core/functor"
)

func main() {
intSlice := []int{1, 3, 5, 7}
fmt.Println("Int Slice: ", intSlice)
intFunctor := functor.LiftIntSlice(intSlice)
fmt.Println("Lifted Slice: ", intFunctor)

// Apply a square to our given functor
squareFunc := func(i int) int {
return i * i
}

// Apply a mod 3 to our given functor
modThreeFunc := func(i int) int {
return i % 3
}

squared := intFunctor.Map(squareFunc)
fmt.Println("Squared: ", squared)

modded := squared.Map(modThreeFunc)
fmt.Println("Modded: ", modded)
}

During the execution of this code, we can see that our function manipulation with functors worked as expected. We took our initial intSlice, lifted it into a functor, applied a square to each value with squareFunc, and applied %3 to each value with modThreeFunc:

Functors are a very powerful language construct. A functor abstracts a container in a way that is easily modifiable. It also allows for a separation of concerns—for instance, you can separate iteration logic from calculation logic, functors can be parameterized more simply, and functors can also be stateful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.144.170