r_notes icon indicating copy to clipboard operation
r_notes copied to clipboard

Point out short circuiting behaviour of double boolean operators

Open bobjansen opened this issue 2 years ago • 1 comments

The tutorial points out that && and || are the scalar variants of & and | but doesn't explain why it's useful to have to operators and the more subtle differences. I think it would be worthwhile to point out that

  1. && and || don't evaluate the right hand side when not necessary:
> x <- TRUE || stop('Oops')
> x
TRUE
  1. Using them where you need the vectorized version is dangerous:
> (1:2) && (3:4)
[1] TRUE
> if (all((1:2) && (3:4))) message('Oops')
Oops

bobjansen avatar Feb 06 '22 18:02 bobjansen

Yup, good observations. There are a couple things like that, the other example being assignment to the parent environment with <<-. However the problem with explaining those is that they are introduced early before function calls or vectorisation. So I cannot just drop stop() or 1:2 there. And returning to the same operators later doesn't flow well.

For now I just left them there and curious readers will find out with help(). But will leave this issue hanging, maybe some way of explaining them will come to mind. Or maybe someone will have good suggestions.

karoliskoncevicius avatar Feb 06 '22 20:02 karoliskoncevicius