Danack / RfcCodex

Notes on PHP RFCs, and topics that occur repeatedly on PHP internals
MIT License
207 stars 10 forks source link

chained comparison #27

Closed Danack closed 2 years ago

Danack commented 2 years ago

RFC name

Python allows this:

if (0 <= x <= 10) {...}

Summary

It's nice as it reads nice, but also avoids a problem. That code is equivalent to:

if (0 <= x && x <= 10) {...}

But imagine we had:

if (0 <=foo() <= 10) {...}

and foo() had side-effects then the equivalent code:

if (0 <= foo() && foo() <= 10) {...}

is calling foo() twice. The workaround of:

y = foo()

if (0 <= y && y<= 10) {...}

is even jankier.

Danack commented 2 years ago

notes on it: https://mathspp.com/blog/pydonts/chaining-comparison-operators

Did you know that you can actually chain an arbitrary number of comparison operators? For example, a == b == c == d == e checks if all five variables are the same, while a < b < c < d < e checks if you have a strictly increasing sequence.

Danack commented 2 years ago

Good uses at 4 minute mark: https://www.youtube.com/watch?v=M3GAJ1AIIlA&ab_channel=mCoding

Danack commented 2 years ago

Done https://github.com/Danack/RfcCodex/blob/master/chained_comparison_operators.md