Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Last active December 11, 2015 00:39
Show Gist options
  • Save jonahwilliams/3f5fea9bcaeb00b23ad5 to your computer and use it in GitHub Desktop.
Save jonahwilliams/3f5fea9bcaeb00b23ad5 to your computer and use it in GitHub Desktop.
Parametric Polymorphism ... in my JavaScript?
// @flow
// The Identity Monad
class Container<A> {
value: A;
constructor(x: A) {
this.value = x;
}
map<B>(f: (x: A) => B): Container<B> {
return Container.of(f(this.value));
}
get(): A {
return this.value;
}
static of<B>(x: B): Container<B> {
return new Container(x);
}
}
// Types of a and b are infered by Flow
let a = Container.of(23)
.map(x => x * 2)
.map(x => x.toString())
.get();
let b = Container.of('hello')
.map(x => x.length)
.get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment