Skip to content

Ordering::and_then #1677

Closed
Closed
@digama0

Description

@digama0

From rust-lang/rust#34774:

This seems like an obvious and missing function from std::cmp::Ordering:

impl Ordering {
    pub fn then(self, other: Ordering) -> Ordering {
        match self {
            Ordering::Equal => other,
            o => o,
        }
    }

    pub fn and_then<F: FnOnce() -> Ordering>(self, other: F) -> Ordering {
        match self {
            Ordering::Equal => other(),
            o => o,
        }
    }
}

This is useful for creating comparators which do lexicographic order. The second variant allows for skipping the order calculation if it is not necessary.

To explain the name then / and_then: Java has a similar function for comparators, called thenComparing. The idea is that you can read a comparison function like

self.name.cmp(other.name).then(self.address.cmp(other.address))

as "compare by name, then by address". The then / and_then difference with a closure is inspired by Rust's function names for Option like or (by value) / or_else (by closure).

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions