1

This might be a very simple question, or perhaps have been asked before but I couldn't really find an answer after a brief search here and via google.

So taking the risk of having missed something similar to this, here goes my question. Why is it so that conditional statements checking for intervals are often not supported as they are, but instead implemented as block ifs or using the && operator to bind together the two separate conditions?

Admitted that it's not the whole world if I have to write two lines of more code, but coming from mathematics background, I find it really peculiar that modern compilers cannot do their voodoo on this relatively simple statement.

Is there a particular reason for it for a technical or theoretical perspective?

posdef
  • 6,498
  • 11
  • 46
  • 94

2 Answers2

1

My two cents here: if you write a < b < c in many languages it means (considering that compare operators are often left associative) ((a < b) < c). But a < b returns a boolean, and so (for example if a < b returns true) the successive reduction is (true < c) which in all but an extreme rare case is not what you want to do.

Vincenzo Maggio
  • 3,787
  • 26
  • 42
  • Ok, that's a good point.. But consider the amount of "magic" that compilers seems to do these days, wouldn't it be possible to sort this relatively small problem? – posdef Jul 13 '12 at 11:58
1

I would say that there is no impediment from a technical point of view since some languages do support that kind of comparison:

  • Python (docs)
  • Clojure (docs) -and almost any other lispy language out there
  • Perl 6 (docs)

And Mathematica if I remember right.

What it is sure is that it makes the parsing of the language a bit more complex, and language designers may or may not pay that price if they don't see it as a feature to be used very frequently.

ps. I personally like it but have found myself rarely using it in Python.

pacha
  • 2,992
  • 1
  • 16
  • 18
  • I am not sure about Mathematica, but MATLAB supports it. I have mostly been using Java and Java-like languages where this kind of chaining is not supported. I guess the interesting question is what/how big is the extra complication regarding parsing and how big the price of fixing that complication is compared to other complications... – posdef Jul 13 '12 at 12:32
  • @posdef, definitively. The only other reason that I can think of is that using parentheses in that kind of expression somehow breaks the consistency of the language: `4 > 3 > 2` is not the same than `(4 > 3) > 2` as @Vincenzo points out. In Python the first one renders `True` and the second one renders `False`, which is arguably a bit odd. – pacha Jul 13 '12 at 16:52