Skip to content

kutyel/what-is-a-monad-ts

Repository files navigation

what-is-a-monad-ts

styled with prettier Travis Coveralls

Learn what Monads™️ are in TypeScript!

/**
 * The `Monad` type class combines the operations of the `Chain` and
 * `Applicative` type classes. Therefore, `Monad` instances represent type
 * constructors which support sequential composition, and also lifting of
 * functions of arbitrary arity.
 *
 * Instances must satisfy the following laws in addition to the `Applicative` and `Chain` laws:
 *
 * 1. Left identity: `M.chain(M.of(a), f) <--> f(a)`
 * 2. Right identity: `M.chain(fa, M.of) <--> fa`
 *
 * Note. `Functor`'s `map` can be derived: `A.map = (fa, f) => A.chain(fa, a => A.of(f(a)))`
 *
 */
export interface Nothing {
  readonly _tag: 'Nothing'
}

export interface Just<A> {
  readonly _tag: 'Just'
  readonly value: A
}

export type Maybe<A> = Nothing | Just<A>