Skip to content

Instantly share code, notes, and snippets.

@roman
Created July 26, 2010 20:30
Show Gist options
  • Save roman/491180 to your computer and use it in GitHub Desktop.
Save roman/491180 to your computer and use it in GitHub Desktop.
// need an algebraic data structure
// a..e are defined as meta param names
// f variable will hold all the declared Algebraic Data Types
newdata("Maybe", function(spec){
// the data constructor name as key
// the parameters specified as an array
spec["Just"] = [a];
spec["Nothing"] = [];
});
classtype("Monad", function(spec) {
// spec will have the different methods of a classtype
// each attribute is a function that could have default
// implementations
spec['_bindAction'] = function(monad, fn) {
this.bind(monad, function(_) {
return fn();
}
};
spec['bindAction'] = function() {};
spec['inject'] = function() {};
});
function lookupPerson(id) {
if (id === 12345) {
return f.Just("Roman");
}
else {
return f.Nothing;
}
}
function lookupNumber(person) {
if (person === "Roman") {
return f.Just("555-5555");
}
else {
return f.Nothing;
}
}
// to make an Algebraic Data Type or a newtype an instance
// of a classtype
classtypeInstance("Monad", "Maybe", {
bindAction: function(maybe, fn) {
maybe.match({
'Just': function(x) { return fn(x); },
'Nothing': function() { return f.Nothing; }
});
},
inject: function(a) {
return f.Just(a);
}
});
// to declare
function() {
lookupPerson(12345).bindAction(function(person) {
return lookupPhone(person);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment