Some programming languages, such as Perl, have an infix operator <=>
that returns a three-state comparison. The expression
a <=> b
evaluates to -1, 0, or 1 depending on whether a < b, a = b, or a > b. You could think of <=>
as a concatenation of <
, =
, and >
.
The <=>
operator is often called the “spaceship operator” because it looks like Darth Vader’s ship in Star Wars.
Python doesn’t have a spaceship operator, but you can get the same effect with numpy.sign(a-b)
. For example, suppose you wanted to write a program to compare two integers.
You could write
from numpy import sign def compare(x, y): cmp = ["equal to", "greater than", "less than"][sign(x-y)] print(f"{x} is {cmp} {y}.")
Here we take advantage of the fact that an index of -1 points to the last element of a list.
The sign
function will return an integer if its argument is an integer or a float if its argument is a float. The code above will break if you pass in floating point numbers because sign
will return −1.0, 0.0, or 1.0. But if you replace sign(x-y)
with int(sign(x-y))
it will work for floating point arguments.
Related post: Symbol pronunciation
Now show us how to use this to synthesize the equivalent of FORTRAN arithmetic IF.
There was cmp() in Python 2 days, and the docs provide an alternative¹ as (a > b) – (a < b). Whether you consider that readable given that it depends on treating bools as ints is debatable.
¹ https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons
C++20 standard includes spaceship operator – and uses it to automatically generate all other comparison operators.