rusttuples

How is ordering defined for tuples in Rust?


I was looking at the documentation and found an example code that looked unfamiliar.

std::cmp::Reverse - Rust

use std::cmp::Reverse;

let mut v = vec![1, 2, 3, 4, 5, 6];
v.sort_by_key(|&num| (num > 3, Reverse(num)));
assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);

How does (num > 3, Reverse(num)) define ordering between themselves?

I had a look into documentation for tuple, and it said

The sequential nature of the tuple applies to its implementations of various traits. For example, in PartialOrd and Ord, the elements are compared sequentially until the first non-equal set is found.

That makes sense for equality checks, but it seems to me that it does not give explanation for how > and < acts on tuples.

I did some experiments, but understood nothing.

    println!("{}", (5, 5) > (3, 4)); // true
    println!("{}", (2, 2) > (3, 4)); // false
    println!("{}", (2, 5) > (3, 4)); // false
    println!("{}", (3, 5) > (3, 4)); // true
    println!("{}", (5, 2) > (3, 4)); // true

Solution

  • As what you quoted notes, tuples are compared lexicographically.

    That is, the first elements of each tuple are compared, then if they're equal the second elements are, then the third, etc.. until a non-equal pair is found and provides the ordering of the tuples. If all pairs are equal then the tuples are, obviously, equal.

    println!("{}", (5, 5) > (3, 4)); // true
    

    5 > 3, therefore (5, _) > (3, _)

    println!("{}", (2, 2) > (3, 4)); // false
    

    2 < 3, therefore (2, _) < (3, _)

    println!("{}", (2, 5) > (3, 4)); // false
    

    see above

    println!("{}", (3, 5) > (3, 4)); // true
    

    3 == 3, 5 > 4, therefore (3, 5) > (3, 4)

    println!("{}", (5, 2) > (3, 4)); // true
    

    see first case

    How does (num > 3, Reverse(num)) define ordering between themselves?

    booleans sort false < true, therefore it first orders the elements in two broad categories (numbers 3 or below then numbers above 3) then within each category items are ordered based on their reverse natural order (that is, largest-first). Though it obviously does that in a single pass.