Of all the mundane details that programming bothers me with, operator precedence/arithmetical order of operations pisses me off the most. Pardon the vulgarity, but if you’ve ever had to wonder whether 5 + 6 * 2 was equal to 22 or 17, or even worse–had a bug caused by guessing wrong in that sort of situation, you know how I feel.

 

I like using whitespace to disambiguate that sort of expression for myself, as in 5+6 * 2 (note the lack of space between “5”, “+”, and “2”). This works great; the “5+6” groups together to our eyes because of the lack of space, and is clearly separate from the “*” and “2” because of the intervening whitespace. (If you’re interested: this sort of thing was studied by the German Gestalt psychologists.) The problem with using a scheme like this isn’t that it doesn’t work for us–it works great; the problem is that all programming languages I know of disregard the information contained in the whitespace. So while I’d say 5+6 * 2 equals 22, the computer would say otherwise.

Steve McConnell recommends you “use more parentheses than you think you need” (pg738 in Code Complete, 2nd edition). That solution is very practical, but it amounts to giving in to the language. I’m an idealistic young kid, and I think we should make the languages suit us instead of changing ourselves to suit the languages. I’ve also taken enough philosophy courses that just thinking bores me, so here’s some action:

function thoughtful_evaluate(expression) {
var x = ”;
var chunks = expression.split(/\s/);
for (i in chunks) { var chunk = chunks[i];
if (chunk.match(/^[\+\-\/\*]$/) != null)
// this chunk is a single operator
x += chunk;
else
x += eval(chunk);
}
return eval(x);
}
function compute_results() {
var x = document.getElementById(‘t’).value;
if (x.match(/^[1234567890\+\-\/\*\s]*$/) == null) {
alert(‘invalid expression; only numbers and arithmetic operators are allowed.’);
}
document.getElementById(‘standard_result’).innerHTML = eval(x);
document.getElementById(‘thoughtful_result’).innerHTML = thoughtful_evaluate(x);
}Type an arithmetic expression in the box below and then click “evaluate”.

Below, you see the results of evaluating the above expression under two different schemes: JavaScript’s standard order of operations and my “thoughtful” order of operations which groups expressions based on whitespace.

standard
thoughtful

The code that accomplishes this feat is simple; view source to see exactly how it’s done. The heavy lifting is accomplished in under 10 lines of code, and those aren’t very dense lines either.

Now the real question is, will I find some open source language and implement this thoughtful grouping? We’ll see…