Skip to content

Instantly share code, notes, and snippets.

@bangedorrunt
Last active October 23, 2015 07:21
Show Gist options
  • Select an option

  • Save bangedorrunt/b80861ff5eabc582f7fa to your computer and use it in GitHub Desktop.

Select an option

Save bangedorrunt/b80861ff5eabc582f7fa to your computer and use it in GitHub Desktop.
Functional JavaScript
// Functors apply a function to a wrapped value and then return a wrapped value
// Functors are chainable
// Functor::(a -> b) -> f(a) -> f(b)
class Wrapper {
constructor(val) {
console.log('Created a wrapped value ' + val);
this.val = val;
}
// Functor's `fmap` in Haskell
map(func) {
return new Wrapper(func(this.val));
}
// Monad's `return` in Haskell
static of(val) {
return new Wrapper(val);
}
}
let value = 'Hello World!';
// Functor
Wrapper.of(value).map(_.words).map(_.size);
// Monads apply a function that returns a wrapped values to a wrapped value
// and then return a wrapped value
// Monads are chainable
class Wrapper {
constructor(val) {
console.log('Created a wrapped value ' + val);
this.val = val;
}
// Functor's `fmap` in Haskell
map(func) {
return new Wrapper(func(this.val));
}
// Monad's `>>=` (pronounced bind) in Haskell
flatMap(func) {
return func(this.val);
}
// Monad's `return` in Haskell
static of(val) {
return new Wrapper(val);
}
}
let value = 2;
// Monad
Wrapper.of(value).flatMap(function(x){ return Wrapper.of(x+2)}).flatMap(function(x) {return Wrapper.of(x*-1)});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment