April 2018
Beginner
536 pages
13h 21m
English
A Functor is an object that holds a value and 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:
let double = (x: number) => x + x;
let container = new Container(3);
let container2 = container.map(double);
console.log(container2); // { _value: 6 }
At this point, it might feel like a Functor 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 ...