Skip to content

Instantly share code, notes, and snippets.

@lupuszr
Created March 28, 2019 07:54
Show Gist options
  • Save lupuszr/91a7106f656b0432288811c6866c02d4 to your computer and use it in GitHub Desktop.
Save lupuszr/91a7106f656b0432288811c6866c02d4 to your computer and use it in GitHub Desktop.
IO monad example in typescript
interface IO<T> {
(unsafeIO: Function): IO<T>;
chain(fn: (a: T) => IO<T>): IO<T>
of(performUnsafeIO: (a: T) => T): IO<T>;
fork(): IO<T>;
map(fn: (a: T) => T): IO<T>;
value: Function
};
type KIO<T> = (a: T) => T;
type FIO<T> = (a: T) => IO<T>;
function IO<T>(this: IO<T>, unsafeIO: (Function)) {
this.value = unsafeIO;
return this;
};
IO.prototype.chain = function<T>(fn: FIO<T>) {
return fn(this.value())
}
function new_(x: any, k: any) {
return new x(k);
}
IO.of = function<T>(performUnsafeIO: KIO<T>): IO<T> {
return new_(IO, performUnsafeIO);
}
IO.prototype.fork = function() {
return new_(IO, this.value());
}
IO.prototype.map = function(fn: Function) {
return new_(IO, () => fn(this.value()))
}
// USAGE
const fn: ((a: number) => number) = a => a + 1.0;
const gn: ((a: number) => string) = g => g + "1.0";
const a = IO.of(() => Math.random()).map(fn).map(a => a * 2).chain(p => IO.of(fn)).chain((k) => IO.of(() => Math.random() + k)).fork()
console.log(a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment