Since I've been reading Programming Collective Intellegence (along with everyone else!) and Dave always telling me this stuff needs to be done as a tree ("LISP, NICK! LISP!") I started thinking down that path.
Then I realized that HTML is a tree, and quickly coded up this useless calculating proof of concept: HTML programming!
<body>
<div class="add">
<div class="power">
<div>x</div>
<div>2</div>
</div>
<div class="multiply">
<div>5</div>
<<div>x</div>
</div>
<div>4</div>
</div>
</body>
This is the "Code". It's a polynomial, x^2+5x+4. And then the "interpreter":
function writeExpression(action, actors) {
//console.debug(action,actors);
if (action == 'add') action = '+';
if (action == 'subtract') action = '-';
if (action == 'multiply') action = '*';
if (action == 'power') action = 'Math.pow(';
var openParen = action.indexOf("(");
if (openParen > -1) {
action += actors.join(",")+")";
return action;
} else {
return actors.join(action);
}
}
function depthFirst(el) {
if (el.childElements().length == 0) return el.innerHTML;
var children = [];
for(var i = 0; i < el.childElements().length; i++) {
children.push(depthFirst(el.childElements()[i]));
}
var expression = writeExpression(el.className, children);
//console.log(expression);
return expression;
}
function parse() {
var code = depthFirst($(document.body));
$(document.body).insert("<br/>"+code);
x = prompt('X = ?');
eval("fun = function(x) {return "+code+";}; alert('f(x) = "+code+"\\nf("+x+") = '+fun(x));");
}
It's just a depth first search that then decodes the class name into an operator and returns the equation for that branch.
1 comment:
Keep up the good work.
Post a Comment