Skip to content

@igstan /state-monad.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.