Created
July 26, 2010 20:30
-
-
Save roman/491180 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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