Skip to content

Instantly share code, notes, and snippets.

@igstan
Created May 1, 2011 23:09
Show Gist options
  • Save igstan/950972 to your computer and use it in GitHub Desktop.
Save igstan/950972 to your computer and use it in GitHub Desktop.
State Monad in JavaScript
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment