openlang

3 + 4 * 2 is 14, and that is the easy part

Everyone new to Smalltalk meets 3 + 4 * 2 early and gets told it's 14, because binary messages go left to right with no arithmetic precedence at all. That part sticks after one demo (it really is just two sends, + to 3 and then * to whatever came back, and numbers get no special treatment, which people find either refreshing or mildly insulting).

What trips learners for much longer is the other half of the rule. Unary messages bind tighter than binary ones, and binary tighter than keyword ones. So 2 + 3 squared is 11, because squared goes to 3 before anything else happens, and 2 raisedTo: 3 + 1 is 16, because the keyword message waits for its argument to finish.

I'm tempted to teach the three levels first and use the arithmetic only as the example of the binary rule, instead of opening with arithmetic as the famous oddity. Not sure yet that it's better. It might stop people calling it a quirk, which would already be something.

The conversation continues 1

Follow the reasoning
  1. Permalink

    Rule first is the order I'd pick, with the rule stated as precisely as the examples. Three levels, unary then binary then keyword, and left to right within a level. Then each example tests one clause. 2 + 3 squared checks unary over binary. 3 + 4 * 2 checks left to right. 2 raisedTo: 3 + 1 checks binary over keyword. A learner who predicts all three has the rule, and one who misses tells you which clause is missing. SQL readers may be an easy audience, since a OR b AND c meaning a OR (b AND c) is a precedence table most of them have had to look up at least once.

Other sides of the same question

  1. round(2.5) gives 2, and learners don't believe it

    Learners keep guessing that round(2.5) is 3, and both languages I reach for say 2. Python gives the integer 2, Julia gives 2.…

  2. Translating old CoffeeScript by hand is a decent JavaScript lesson

    An unfashionable exercise that works better than it has any right to. Give a learner a small old CoffeeScript file and have t…

  3. (x, x) does not mean both halves are equal

    Learners keep reading OCaml's (x, x) as "both halves are equal". It isn't that, and it isn't even legal. A newcomer tends to…

    Replies 5ocaml