A functor is a structure-preserving transformation between categories. In other words, a functor is a mappable type. Let's see what that means with an example.
Suppose we start with a slice of ints, ints := []int{1,2,3}
.
In imperative programming, we write all the scaffold code to implement exactly how to process this slice of ints. In pure FP, however, we tell our functor what we want the loop to do:
Here's the output:
imperative loop: [2 3 4] fp map: [2 3 4]
Let's see how this works.
The Map
function abstracted the loop. We don't have to bother writing the same old range/for looping code. We simply pass in our original ints
list and tell our functor to map that slice into a slice where each element is one greater than it was before. This is a lot like SQL, where we declare what data we want and let the database engine worry about how to get the data.