Question

I'm writing a shunting yard algorithm in Javascript for boolean logic, and I'm running into a hitch with order of operations. The operations that I allow are:

and, or, implies, equals(biconditional), not, xor, nor, nand

However, I don't know what the precedence is for these. As of now, I have:

not>equals>implies>xor>nor>nand>or>and

Is this correct? Is there any standard I can use, similar to the PEMDAS/BODMAS system for numbers?

Was it helpful?

Solution

The reason you are having such a hard time finding a definition of precedence of those operators for JavaScript is that:

  1. Precedence only comes into play when using infix notation. Since you mention the shunting yard algorithm I take you intend to use infix notation.
  2. Each language can define it's own precedence and since you are creating a DSL, you create the precedence, but it must be consistent.
  3. Those names are really prefix function names and infix is more common with symbols for operators than names. You should be using operators and not function names:

    and &
    or |
    implies →
    equals (biconditional) ↔
    not !
    xor ⊕
    nor ⊽
    nand ⊼

  4. When parsing you convert infix to prefix or postfix, so the operators symbols should change to function names if you are building an intermediate form such as an AST.
  5. You didn't mention associativity which you will need for NOT.
There appears to be no standard as noted by the differences between these two respectable sources.

From "Foundations of Computer Science" by Jeffrey D. Ullman

Associativity and Precedence of Logical Operators

The order of precedence we shall use is
1. NOT (highest)
2. NAND
3. NOR
4. AND
5. OR
6. IMPLIES 7. BICONDITIONAL(lowest)

From Mathematica

NOT
AND
NAND
XOR
OR
NOR
EQUIVALENT
IMPLIES

OTHER TIPS

It's seems there is no a standart.

I've a book (Digital design by Morris Mano) that says NOT>AND>OR. this is an accepted opinion.

About the rest, i've found few opinions. This guy think EQUIV is the lowest (Wikipedia assist). but this guy think EQUIV is in the middle XOR>EQUIV>OR (with few references).

Another disagreement is about XOR place. here this third guy agree with the second guy :)

In short, two opinions:

1) NOT>AND>NAND>XOR>EQUIV>OR>NOR (ignoring NOR)

2) NOT>AND>NAND>NOR>OR>IMPLIES>XOR>EQUIV

Note: only the NOT>AND>OR part is certified academically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top