josdejong/mathjs — pull request #2 by bkiers (2013-03-20 20:58:57+00:00)
Title: Made pow-operator right associative.

Hi Jos, as usual with your work: great stuff! I did find a little bug though: your parser handles the power operator like any other binary operator (left associative), while the power operator is (in most cases) right associative. I.e., the expression `a^b^c` is now being parsed as:

^
/ \
^ c
/ \
a b

while it should be parsed as:

^
/ \
a ^
/ \
b c

Since the parser is a LL (top-down) parser, this desired structure is a bit tricky to get. A possible solution:

For the input `"a^b^c"` the parser would first create `(^ a b)` and would then encounter `"^c"`. Now instead of creating the AST `(^ (^ a b) c)`, you do the following inside `Parser.prototype.parse_pow`:

* make the 'old' left child of `(^ a b)` (node `a`) the left child of the new node: `(^ a (^ . b))`
* move the old right child, node `b`, to the left: `(^ a (^ b . ))`
* put the new node, `c`, to the right of `b`: `(^ a (^ b c))`

My pull request has the scheme above implemented, including some unit tests.

Cheers,

Bart.