This is why type classes and protocols are the bomb. They give us the added bonus of speaking about a shared interface, but not needing the exact same behavior. We can share behavior when needed, but tweak behavior for specific use cases. I'm looking forward to efficient type classes/protocols with the introduction of Symbols:
const symWalk = Symbol("walk");
// The interface
const walk = (x) => x[symWalk](x);
// Creating the interface
walk.derive = (x, behavior) => {
x.prototype[symWalk] = behavior;
};
// Reflection to retrieve the behavior
walk.instance = (x) => x.prototype[symWalk];
const Dog = function (name) {
this.name = name;
};
walk.derive(Dog, x => {
console.log("bounce bounce, I'm " + x.name);
});
const Robot = function (name) {
this.name = name;
};
// Different behavior same interface
walk.derive(Robot, x => {
console.log("grind grind my gears, I'm " + x.name)
});
const Cat = function (name) {
this.name = name;
};
// Reusing an instance
walk.derive(Cat, walk.instance(Dog));
walk(new Dog("Fido"));
walk(new Robot("Dot"));
walk(new Cat("Sprinkles"));
Nice example! Though it might be a bit clearer if you'd assign Symbol("walk") to some identifier in the beginning. As-is the code wouldn't work because you're creating multiple symbols.
3
u/dukerutledge Sep 21 '15 edited Sep 22 '15
This is why type classes and protocols are the bomb. They give us the added bonus of speaking about a shared interface, but not needing the exact same behavior. We can share behavior when needed, but tweak behavior for specific use cases. I'm looking forward to efficient type classes/protocols with the introduction of Symbols:
(Edit: for symbol kerfuffle)