Type-oriented programming/Functors

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

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

The map method must satisfy some formal requirements that we ignore here for now. The important point is that map takes a function of type Func[T,U] (where U is a type argument of the method) and returns an instance of type Self[U], that is, the same functor possibly with a different type argument. You’ve already met the Maybe 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 Maybe to explain what a monad is and how a generic Monad 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 main {} block.