4

Generally (perhaps always) in programming languages, unary operators have the highest precedence. In some langauges, such as Standard ML, one can dynamically change the precedence of binary operators at run time.

But what if we have a language where binary operators had higher precedence than unary ones? Do such languages exist? And how would we interpret certain cases? For example, let's say binary + had higher precedence than unary prefix @. In some cases this is obvious because it would mean that

@x+y

would parse as

@(x+y)

rather than

(@x)+y

BUT, how would we parse

x + @y

Would it be a syntax error (as in it cannot be parsed) or should it parse as x+(@y)? I don't mean for this to necessarily be an opinion question; I am more interested to know if any real programming languages exist with high-precedence binary operators, and if so, what do they do.

Gilles 'SO- stop being evil'
  • 44,159
  • 8
  • 120
  • 184
Ray Toal
  • 287
  • 1
  • 7

2 Answers2

1

In Perl, the 'not' operator has lower precedence than +. The expression (false + not 1) evaluates just fine.

mhum
  • 2,350
  • 14
  • 18
0

OCaml also has if operator which has less precedence than, say, +:

1 + if true then 2 else 3 * 4

is interpreted by OCaml as:

1 + ( if true then 2 else (3 * 4) )

There if "covers" the (3 * 4) operation inside of itself.

Note that if then else in OCaml is not an if-statement, it's an if-expression, similar to C's ?: ternary operator. But if in Ocaml is a prefix operator, so it's similar to your @ example.

This phenomenon is well-known in the literature on parsing, see for example, Precedences in specifications and implementations of programming languages (1995) by Anna Aasa.

shitpoet
  • 111
  • 2