Type-oriented programming/Functors

A functor is a type operator equipped with a  method declared as follows:

type Functor[T] { func map[U](f Func[T,U]) Self[U] }

The  method must satisfy some formal requirements that we ignore here for now. The important point is that  takes a function of type  (where   is a type argument of the method) and returns an instance of type , that is, the same functor possibly with a different type argument. You’ve already met the  functor:

type Maybe[T] : Functor[T] { property val T

func map[U](f Func[T,U]) Self[U] { return new Self[U] { val = self.val.isNil ? nil : f(self.val) } }

func description String { return self.val.isNil ? "none" : self.val.description } }

In the next section, we’ll use  to explain what a monad is and how a generic  type can be implemented.

NB: The pseudocode can be tried out using the Funcy app, which can be downloaded for free from Apple’s App Store (iOS/macOS), Google Play (Android) or Amazon Appstore. The code to be executed must be placed in a  block.