Created
January 18, 2019 22:25
-
-
Save cowboyd/df2286d2e9fcd94c3fa6d4a263946bf6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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