April 2018
Beginner
536 pages
13h 21m
English
The following Maybe data type is a Functor and an Applicative, which means it contains a value and implements the map method. The main difference with the preceding implementation of Functor is that in the Maybe Functor, the value contained by the data type is optional:
class MayBe<T> {
public static of<TVal>(val?: TVal) {
return new MayBe(val);
}
private _value!: T;
public constructor(val?: T) {
if (val) {
this._value = val;
}
}
public isNothing() {
return (this._value === null || this._value === undefined);
}
public map<TMap>(fn: (val: T) => TMap) {
if (this.isNothing()) {
return new MayBe<TMap>();
} else {
return new MayBe<TMap>(fn(this._value));
}
}
}
As we can see in the preceding implementation of the map method, the mapping ...