Skip to content

Instantly share code, notes, and snippets.

@hsk
Created July 4, 2014 05:26
Show Gist options
  • Save hsk/77c338e2a37cb2c177fb to your computer and use it in GitHub Desktop.
Save hsk/77c338e2a37cb2c177fb to your computer and use it in GitHub Desktop.
var traits = {};
var insts = {};
function trait(name, methods) {
traits[name] = methods;
insts[name] = {};
}
function struct(name, params, impls, body) {
function findTraitName(x) {
for (var traitName in traits) {
if (x in traits[traitName]) return traitName;
}
}
for (var x in body) {
// インターフェイスを取得
var inst = insts[findTraitName(x)];
if (!(name in inst)) inst[name] = {};
inst[name][x] = body[x];
}
return function() {
var i = 0;
for (var x in params) {
this[x] = arguments[i];
i++;
}
this.typeName = name;
};
}
trait("Eq1", {
eq1: ["fun", ["self", "self"], "bool"]
});
trait("Eq2", {
eq2: ["fun", ["self", "self"], "bool"]
});
var N = struct("N", {
"x": "int"
}, ["Eq1", "Eq2"], {
"eq1": function(s, a) {
return s.x == a.x;
},
"eq2": function(s, a) {
return s.x == a.x;
}
});
var i = new N(20);
var j = new N(20);
console.log(i.x);
console.log(insts.Eq1[i.typeName].eq1(i, j));
console.log(insts.Eq2[i.typeName].eq2(i, j));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment