Skip to content

Instantly share code, notes, and snippets.

const promise: Promise<A>;
const a = await promise;
// a of type A
const monad: Monad<B>;
const b = yield monad;
// b is of type B, but not automatically inferred
fetchA().then(fetchB).then(fetchC).then(fetchD);
interface Promise<A> {
then<B>(callback: (a: A) => B | Promise<B>): Promise<B>
}
type Monad<A> = Array<A>;
function of<A>(a: A): Monad<A> {
return [a];
}
function flatMap<A, B>(monad: Monad<A>, cb: (a: A) => Monad<B>): Monad<B> {
return monad.flatMap(cb);
}
multi function rightTrianglesG(maxLengthC: number) {
const c = pick range(1, maxLengthC + 1);
const a = pick range(1, c);
const b = pick range(1, a);
pick where(a**2 + b**2 === c**2);
return [a, b, c] as const;
}
multi function where(cond: boolean) {
if (cond) return pick [];
fetchA()
.then((a) => fetchB(a)
.then((b) => fetchC(b)
.then((c) => fetchD(c))))
// this can be safely refacoted as
fetchA().then(fetchB).then(fetchC).then(fetchD)
// Given
declare const monad: Monad<A>
declare function f(a: A): Monad<B>;
declare function g(b: B): Monad<C>;
// Then
flatMap(flatMap(monad, f), g) === flatMap(monad, (a) => flatMap(f(a), g))
@kasperpeulen
kasperpeulen / monad-functions.ts
Last active November 20, 2020 10:42
Monad functions
function of<A>(value: A): Monad<A>;
function flatMap<A, B>(monad: Monad<A>, callback: (a: A) => Monad<B>): Monad<B>;
// Given
declare const monad: Monad<A>;
// Then
flatMap(monad, a => of(a)) === monad
// === means both parts are equivalent
// what equality means can be defined by the monad
// Given
declare const a: A;
declare function f(a: A): Monad<B>;
// Then
flatMap(of(a), a => f(a)) === f(a);
// === means here that both parts are equivalent
// what equality means can be defined by the monad