Thread: unary operators, precedence, grouping

unary operators, precedence, grouping

From
"woger151"
Date:
I defined a function, count_nonnull, to return 1 if not null, 0 otherwise.
Then I defined a corresponding unary operator <~~. I wanted it for
expressions like <~~ item_1 + <~~ item_2. But because precedence of
user-defined ops is pretty low, I had to rewrite this as <~~(item_1) +
<~~(item_2), which is already no more efficient in use of parentheses than
count_nonnull.

Even worse, however, it turns out that _more_ parentheses were needed:
(<~~(item_1)) + (<~~(item_2)).

Why wouldn't <~~(item_1) + <~~(item_2) be parsed as (<~~(item_1)) +
(<~~(item_2))?




Re: unary operators, precedence, grouping

From
Tom Lane
Date:
"woger151" <woger151@jqpx37.cotse.net> writes:
> Why wouldn't <~~(item_1) + <~~(item_2) be parsed as (<~~(item_1)) +
> (<~~(item_2))?

Because it's parsed as
    <~~ ( (item_1) + ( <~~ (item_2) ) )
"+" binds more tightly than any non-built-in operator, per the
precedence chart in the manual:
http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-PRECEDENCE
so this interpretation is preferred over the alternative
    ( <~~ (item_1) ) + ( <~~ (item_2) )
Those are the only two possibilities without getting into right-unary
operators, which the parser is generally designed not to do if it can
avoid it.

            regards, tom lane