The Functor type has two main characteristics:
- It holds a value
- It implements a method named map
The following code snippet declares a class named Container. This class can be considered a Functor:
class Container<T> {
private _value: T;
public constructor(val: T) {
this._value = val;
}
public map<TMap>(fn: (val: T) => TMap) {
return new Container<TMap>(fn(this._value));
}
}
We can use the container as follows:
const double = (x: number) => x + x;
const container = new Container(3);
const container2 = container.map(double);
console.log(container2); // { _value: 6 }
At this point, you may think that the Functor type is not very useful because we have implemented the most basic version possible. The next two sections implement two Functors known as Maybe and Either. These two Functors are much more useful and will demonstrate...