We can think of a functor as a container, which contains one type of item.

The other requirement for a container to be a functor is that we need an implementation of the fmap function for that container type. The fmap function applies a function to each item in the container without modifying the container or structure in any way.

func fmap[A, B any](f func(A) B, aContainerOfA Container[A]) Container[B]

The classic example, which you might recognize from Hadoop’s MapReduce, Python, Ruby or almost any other language you can think of, is the map function for a slice:

func fmap[A, B any](f func(A) B, as []A) []B {
    bs := make([]B, len(as))
    for i, a := range as {
        bs[i] = f(a)
    }
    return bs
}

meaning that functors are just:

  • an abstract name for a container and
  • that we can apply a function to the items inside the container

https://www.math3ma.com/blog/what-is-a-functor-part-1

https://www.adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html

https://bartoszmilewski.com/2015/01/20/functors/


🌱 Back to Garden