I'd be interested to know whether there are programming languages which have "shorthand equality constructs" (I just made that term up, but not sure how to describe it).
So rather than the normal:
if (X == 1 || X == 2)
A kind-of shorthand equality check, like this: ?
if (X == 1 || 2)
I understand tha开发者_StackOverflowt there are many for & againsts for this sort of construct. And that I can create functions to do something similar, but I'd be interested whether there are languages that enable you to do out of the box.
EDIT
Thanks Michael for helping me clarify things, I like the way Python does it.
I'll try and explain better, as looking at my question above it doesn't explain very well.
Rather than checking for something within a collection, or creates a collection in the background.
I'm wondering if there are programming languages that when only defining the left hand variable once, it will automatically create the left and right for you.
So writing this:
if (X == 1 || 2 || 3)
Would actually create
if (X == 1 || X == 2 || X == 3)
I realise this pseudo synatx isn't hugely useful and that creating the collection is a fine way of doing it. But wondered if it exists anywhere.
I'm not aware of anything with that syntax, but it is closely related to testing for set membership, which many languages do include, either as a language construct or in a library.
For example, consider this bit of Python:
x = 1
if x in {1, 2}:
#do something
That works in Python 2.7+, where there is syntax for set literals. Earlier versions of Python would construct the set as:
x = 1
if x in set([1, 2]):
#do something
Apart from the syntactic difference, the above set-based approach also differs in that all the possible values are eagerly evaluated. You couldn't, for example, do this:
x = 1
if x in {1, 2/0}:
#do something
You'd get an error for dividing by zero.
Bourne shell:
case $x in one | 2 | thr33 | f0re) echo less than six;; esac # spot logic error
精彩评论