Monday, September 22, 2008

Chaining condition

I was reading a python code and discovered this useful feature.

if LOWER < x < UPPER

do_something


I have expressed this "if LOWER < x and x < UPPER" until I discovered chaining expression like this.
Perl and Ruby didn't accept chaining expression. C and C++ will not work because, (let's see the parsing)

1. C replaces expression with result of evaluation. Therefore, '1 < x < 10' expression will be '( (1 < x) < 10 )' and it will be evaluated to non-zero for any x.

2. C++ also replaces expression, but it knows boolean (true/false). Therefore, '1 < x < 10' expression will be either 'true < 10' or 'false < 10'. Since C++ is strong-typed language, this expression requires support of additional function like "boolean operator<(bool&, int&)". If it is supported, it should also support "boolean operator<(int&, bool&)". Now, int is not the only comparable. Beginning with float and double, signed/unsigned char, etc. It gets ugly very easily. Another approach will be replace true to (int)1 and false to (int)0 so that it can leverage existing framework. Anyway, end result is not related to the result of '1 < x < 10'

3. Due to this nature, supporting this expression in dynamic language isn't simple problem. For example of '( (1 < x) < 10)' case, inner expr can be any type based on 'what x is', the interpreter should be able to handle this fine.

Anyway, "1 < x < 10" is more elegant than " (1 < x) and (x < 10)".

No comments: