Functors

In Chapter 3, Types and Type Casting, we talked a little about category theory. Here we go a little further in category theory and talk about Functors. A Functor contains morphisms such as a map function, which transforms the Functor. We can think about a Functor as a functional design pattern.

Knowing category theory is great, but we do not have to. So simply put, a Functor is a structure or container that we can map over. In other words, a Functor is any type that implements the map function. Examples of Functors are Dictionary, Array, Set, Optional, and Closure types.

A Functor applies morphisms or functions to the values it contains, instead of itself. Suppose if we call a function such as doSomething(param: Double), then it will require a Double argument to be passed as a parameter. If we have an Optional<Double>, doSomething(param: Double) will not know how to deal with it. But as Optional<Double> is a Functor, it will understand how to take doSomething and execute it on the value inside itself, then return a new Optional.

Simply put, whenever we talk about Functors, the first thing that should come to our mind is containers that we can call the map function over them and transform them.

We will talk about the map function in more detail in the upcoming sections and explore the usage of Functors.

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

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