compare(obj1, obj2)

If obj1 is less than obj2, return -1. If obj1 is greater than obj2, returns 1. If obj1 is equal to obj2, returns 0.

For sequence objects like strings and lists, a lexicographical comparison is done. First the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. For strings, character comparison is used, for lists and arrays compare is called recursively for each element and for numeric arrays number comparison operators are used.

Compare is a generic function by default and can be overridden for custom data types without an explicit declare generic.


let s1 = "abcd"
let s2 = "xyz"
compare(s1, s2)
// -1
compare(s1, string_upcase(s2))
// 1

compare([1, 2, 3], [3, 2, 1])
// -1
compare([1, 2, 3], reverse([3, 2, 1]))
// 0

// implementing the comparison operators for a custom type:
record point(x, y)

let p1 = point(x = 10, y = 20)
let p2 = point(x = 20, y = 30)
p1 < p2
//> error: compare_not_supported

function pointc(p1)
  | 'compare -> ^(p2) compare(point_x(p1), point_x(p2))

let pc1 = pointc(p1)
pc1 < p2
// true
pc1 > p2
// false

Also see:


Core Module Index | Contents