On 9/4/14, 5:03 PM, "Nordlöw" wrote:
Are there any programming languages that extend the behaviour of
comparison operators to allow expressions such as

     if (low < value < high)

?

This syntax is currently disallowed by DMD.

I'm aware of the risk of a programmer misinterpreting this as

     if ((low < value) < high)

Is this the reason why no languages (including D allows it).

I'm asking for in some cases, where value is a long expression, it would
be a nice syntatic sugar to use.

Crystal has that syntax:

~~~
def foo
  puts "Computing!"
  a = 0
  10.times do |i|
    a += i
  end
  a
end

if 0 < foo <= 45
  puts "Yes"
end
~~~

Prints:

Computing!
Yes

That's because the middle expression in the comparison is first assigned to a temporary variable, so `foo` is only invoked once. This makes both the code more readable, efficient and saves the programmer from having to save that value to a temporary variable itself.

I guess D doesn't have it because it has (...why?) to be compatible with C's semantic. Also, as you can see, it's not that trivial to implement because you need to assign that value first to a temporary variable.

Reply via email to