Skip to content

Instantly share code, notes, and snippets.

@Twisol
Created March 12, 2013 09:16
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 Twisol/5141427 to your computer and use it in GitHub Desktop.
Save Twisol/5141427 to your computer and use it in GitHub Desktop.
Reification of JavaScript function semantics. JavaScript functions can return with either a regular result or an exception, which propagate through code differently. By catching exceptions and combining the two paths through a sum type, more interesting symmetries can be observed.
// data Result e a = Return a | Raise e
Result = function() {};
Return = function(value) { this.value = value; };
Raise = function(value) { this.value = value; };
// inheritance
Return.prototype = Object.create(Result.prototype);
Raise.prototype = Object.create(Result.prototype);
// identity functions
// id is identity over then
id = function(x) { return x; };
// raise is identity over otherwise
raise = function(e) { throw e; };
// fmap
Return.prototype.then = function(onReturn) {
if (typeof onReturn !== "function")
onReturn = id;
var result;
try {
result = onReturn(this.value);
} catch (e) {
return new Raise(e);
}
return new Return(result);
};
Raise.prototype.then = function(onReturn) {
return this;
};
// a different fmap
Return.prototype.otherwise = function(onRaise) {
return this;
};
Raise.prototype.otherwise = function(onRaise) {
if (typeof onRaise !== "function")
onRaise = raise;
var result;
try {
result = onRaise(this.value);
} catch (e) {
return new Raise(e);
}
return new Return(result);
}
/*
* var result = new Return(42)
* .then(stepOne)
* .then(stepTwo)
* .then(dangerWillRobinson);
*
* result.otherwise(logPotentialProblem);
*
* var nextResult = result.then(movingOn);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment