16

I am learning Erlang from the LearnYouSomeErlang web-book. One thing that struck me while learning was the non short-circuiting boolean conjunction and disjunction operators viz; and and or. What are the use cases for these operators? Why would you want to use them instead of andalso and orelse?

missingfaktor
  • 90,905
  • 62
  • 285
  • 365
  • Tagged with `Logic Programming` because I was told that this has something to do with Erlang's origins in Prolog. – missingfaktor Nov 11 '11 at 07:05
  • Related: [When to prefer `and` over `andalso` in guard tests](http://stackoverflow.com/questions/6025132/when-to-prefer-and-over-andalso-in-guard-tests). – Kijewski Nov 11 '11 at 18:36

3 Answers3

14

It used to be (until R13A) that andalso and orelse weren't tail recursive. See http://www.erlang.org/eeps/eep-0017.html for details. I don't think there is a good reason to use and/or in new programs.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
5

I see them as doing different things and use them as such:

  • and/or as logical operators where I want to compare the logical values. As they are strict I automatically get type-checking and I KNOW exactly what has been called.
  • andalso/orelse for control, much like && and || in C.

Seeing errors are defined in erlang I feel it is good to know what has been executed and how it went.

rvirding
  • 20,848
  • 2
  • 37
  • 56
  • 1. `andalso` and `orelse` can also be used as logical operators. 2. I didn't understand the bit about type-checking. 3. Knowing what has been called shouldn't matter with referentially transparent expressions; it is only relevant in the context of side-effects. – missingfaktor Nov 11 '11 at 16:23
  • I think what Robert is saying is that sometimes you want all operands to be evaluated so that they can raise exceptions, even if they are not necessary for the evaluation of the predicate. It's a good point. – dsmith Nov 11 '11 at 18:51
  • @dsmith: Yes, both that and to check that they actually return boolean values. I am perhaps being overly cautious but it is good to catch errors as early as possible. – rvirding Nov 11 '11 at 23:35
4

The and/or operators are simply much older. The andalso/orelse operators are later additions. A use case for and/or today could be when you just want to perform some simple boolean operations and horizontal space is more important than possibly saving a couple of machine cycles. For example:

X = Y and (A or B),

rather than

X = Y andalso (A orelse B),

is a bit easier on the eyes.

For reasons of backwards compatibility, it wasn't possible to just change the behaviour of the original and/or to become short-circuiting, so new keywords were needed. The names andalso/orelse come from Standard ML.

RichardC
  • 10,412
  • 1
  • 23
  • 24