Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created January 18, 2019 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboyd/df2286d2e9fcd94c3fa6d4a263946bf6 to your computer and use it in GitHub Desktop.
Save cowboyd/df2286d2e9fcd94c3fa6d4a263946bf6 to your computer and use it in GitHub Desktop.
/**
* Model stateful computations (those that return a result, but also
* have the side effect of altering some shared context).
* Each stateful computation, is a function that takes a current
* state, and returns two values, the result, `r`, and the new shared
* state `s'`.
*
* In other words, a function `s => [r, s']`
*
* The State monad allows you to compose these effectful computations
* into a starting state that allows you to pipeline values.
*/
class State {
static of(x) {
return new State(s => [x,s]);
}
constructor(compute) {
this.compute = compute;
}
flatMap(fn) {
let { compute } = this;
return new State(s => {
let [ result, newState ] = compute(s);
let computation = fn(result);
return computation.compute(newState);
});
}
set(value) {
return new State(() => [null, value]);
}
}
export default function Constructor(compute) {
return new State(compute);
}
Constructor.of = State.of;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment