Monad

We are going to finish our introduction to algebraic data types by learning about monads. A Monad is a Functor, but it also implements the Applicative and Chain specifications.

We can transform the previously declared Maybe data type into a Monad by adding two extra methods named join and chain:

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)); } } public join() { return this.isNothing() ? Nothing.of(this._value) ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.