Order

The convention is to name the module alias after the file name it is defined in:

import Order "mo:base/Order";

On this page

Public type Order

Function isLess
Function isEqual
Function isGreater
Function equal

Public Type

The Order variant type is used to represent three possible outcomes when comparing the order two values.

type Order = {
    #less;
    #equal;
    #greater;
};

When comparing the order of two values, we could either return:

  • #less when the first value is less than the second value.
  • #equal when both values are equal.
  • #greater when the first value is greater than the second value.

Some types are naturally ordered like number types Nat and Int. But we may define an order for any type, even types for which there is no obvious natural order.

type Color = {
    #Red;
    #Blue;
};

func sortColor(c1 : Color, c2 : Color) : Order {
    switch ((c1, c2)) {
        case ((#Red, #Blue)) { #greater };
        case ((#Red, #Red)) { #equal };
        case ((#Blue, #Blue)) { #equal };
        case ((#Blue, #Red)) { #less };
    };
};

Here we define an order for our Color variant by defining a function that compares two values of Color and returns an Order. It treats #Red to be #greater than #Blue.

Order.isLess

func isLess(order : Order) : Bool
import Order "mo:base/Order";

let order : Order.Order = #less;

Order.isLess(order);

Order.isEqual

func isEqual(order : Order) : Bool
import Order "mo:base/Order";

let order : Order.Order = #less;

Order.isEqual(order);

Order.isGreater

func isGreater(order : Order) : Bool
import Order "mo:base/Order";

let order : Order.Order = #less;

Order.isGreater(order);

Order.equal

func equal(o1 : Order, o2 : Order) : Bool
import Order "mo:base/Order";

let icpToday : Order.Order = #less;

let icpTomorrow : Order.Order = #greater;

Order.equal(icpToday, icpTomorrow);