Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top