public
Last active

State Monad in JavaScript

  • Download Gist
state-monad.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
var push = function (value) {
return function (stack) {
var newStack = [value].concat(stack);
return { value:undefined, stack:newStack };
};
};
 
var pop = function () {
return function (stack) {
var value = stack[0];
var newStack = stack.slice(1);
return { value:value, stack:newStack };
};
};
 
var bind = function (stackOperation, continuation) {
return function (stack) {
var result = stackOperation(stack);
return continuation(result.value)(result.stack);
};
};
 
var result = function (value) {
return function (stack) {
return { value:value, stack:stack };
};
};
 
var evalStack = function (stackComputation, initialStack) {
var result = stackComputation(initialStack);
return result.value;
};
 
var execStack = function (stackComputation, initialStack) {
var result = stackComputation(initialStack);
return result.stack;
};
 
var runStack = function (stackComputation, initialStack) {
return stackComputation(initialStack);
};
 
var computation0 = bind(push(4), function () {
return bind(push(5), function () {
return bind(pop(), function (value0) {
return bind(pop(), function (value1) {
return result(value0 + ":" + value1);
});
});
});
});
 
var computation1 = bind(
push(2), function () { return bind(
push(3), function () { return bind(
pop(), function (value0) { return bind(
pop(), function (value1) {
return result(value0 + ":" + value1);
});
});});});
 
var composedComputation = bind(computation0, function (value0) {
return bind(computation1, function (value1) {
return result(value0 + ":" + value1);
});
});
 
var initialStack = [];
var finalResult = runStack(composedComputation, initialStack);
 
console.log(finalResult);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.