Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Boolean evaluation?  RSS feed

 
Pete Tyo
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am confused on how to evaluate a Boolean expression. Take for example
P && Q || !P && !q
Okay, I was under the impression ! has the higher precedence so I would evaluate (!p & !q) first. After asking my professor he said I would evaluate P && Q first if they evaluate to True then the compiler doesn't go any further (short circuit). So what exactlly is the precedence have to do with anything?
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, short ciruiting means that as soon as the program knows that an expression is true or false, it acts, as opposed to checking every single term.

For instance, if we have the statement p || q, and we find p to be true, we don't care what q is, because the statement is automatically true. Similarly, if we have p && q, and we know p to be false, we don't look at q.

so, in your example of

P && Q || !P && !Q

we first look at the left side of the big or. If it is true, we short circuit. Now, in evaluating that left side, we follow the order of operations. So if our big statement was

!P && Q || !P && !Q,

we first check the left side, which is not-p AND q, because not comes before and. If and came first, the left side would be not (p AND q)

dig?
 
Pete Tyo
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes that does help. I appreciate the help.

Thanks,

Pete
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The order of precedence stuff is tough to remember and I try not to rely on it. If I have to do anything tricky I use parens to make the order explicit.

&& is higher than || so your test is:

( P && Q ) || ( !P && !Q )

The ! has higher precedence yet which binds it to the following P or Q. If we didn't know that we might wonder if your expression meant:

!(P && !Q) --- or --- (!P) && (!Q)

For fun, see if these give the same result:

( P == Q )

!( P ^ Q )
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!