Why are interval comparisons (e.g: x < variable < y) not supported in most “mainstream” languages?

强颜欢笑 提交于 2019-12-24 20:36:42

问题


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?


回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/11468317/why-are-interval-comparisons-e-g-x-variable-y-not-supported-in-most-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!