[Python-ideas] Make max() stable

Andrew Barnert abarnert at yahoo.com
Sat Jan 18 09:26:25 CET 2014


From: Devin Jeanpierre <jeanpierreda at gmail.com>

Sent: Friday, January 17, 2014 11:40 PM


> In a language like C++, you if min and max had the property specified
> by the OP, you might do:
> 
> x = min(a, b);
> y = max(a, b);
> 
> And then x is the smallest, and y is the other one, and it's simple and
> easy and less code than an if statement. I suspect this is where the
> desire comes from.
> 
> In Python, of course, you do x, y = sorted([a, b])


You can write the exact same thing in C++:

    template <typename T> whatever(T a, T b) {
        T x, y;
        tie(x, y) = tuplize(sorted(make_vector(a, b)));

And then x is the smallest, and y is the other one. Plus, all that static type safety makes it even better than the Python version, right? And extending all those helpers to take a variable number of arguments is a simple matter of template metaprogramming (either with a bit of preprocessor help via boost, or with template parameter packs).


Of course you need to write those three helper function templates. Making them work for two parameters is trivial; making them work for an arbitrary number of parameters is a simple matter of template metaprogramming, which any sixth-year C++ student can write in a matter of weeks; it's just partially specializing on parameter packs, which can be done with simple compile-time recursion.

And the advantage is that all that static typing makes sure that you get errors at compile time instead of run time if you make any mistakes—or often even if you don't.


More information about the Python-ideas mailing list