|
 |
>> So... maybe when printing out any given subtree, I make the print
>> function take the precedence of the parent node as an extra argument?
>
> I'd to print the parens (if needed) in the parent call before recursing.
It's easier to do it the other way around. The function only has to care
what the precedence of the current operator is before recursing. The
recursive call can decide what to do about it.
Using this technique, I was also able to "hack" in support for
associativity. For example, in Haskell function application has the
highest possible precedence, and left associativity (because of curried
functions). So, when recursing from a function application call, it
tells the left subtree that the parent's precedence was 8, but it tells
the right subtree that the parent's precedence was 9.
The result is that if you have
$
/ \
/ \
$ $
/ \ / \
A B C D
it prints out as "A B (C D)", which is correct.
(Although, needless to say, I spent a day confusing myself with what
"higher" precedence means, and mixing up left and right associativity.
It probably doesn't help that the function type constructor is
right-associative because the function application operator is
left-associative...)
What can I say? Apparently I'm not very smart.
Post a reply to this message
|
 |