Skip to content

Add a way to combine comparison functions #347

Description

@mlms13

Relude_Ord defines a type for comparison functions type compare('a) = ('a, 'a) => ordering

In that module we already define a by function (and alias it as cmap) which is the essence of being a contravariant functor. What we don't have is an append (or combine) function, which is the essence of being a Semigroup.

But we could, and it would make defining complex compare functions much simpler.

For example, imagine you have a user record that defines first and last name fields, and you want to order these user records by last name, then if last names are equal, by first name.

type t = {
  firstName: string,
  lastName: string,
};

let compare = (a, b) => {
  let byLastName = Ord.by(user => user.lastName, String.compare);
  let byFirstName = Ord.by(user => user.firstName, String.compare);
  Ord.combine(byLastName, byFirstName, a, b);
};

Or, more tersely:

let compare =
  Ord.combine(
    Ord.by(user => user.lastName, String.compare),
    Ord.by(user => user.firstName, String.compare)
  );

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions