Comparison function

Syntax

	$fun.comparator()

Description

Constructs a comparison function for sort() from an access function which calculates a comparison key from a list element. Sorting a list with such a comparator establishes an order of the values supplied by the access function.

Parameters

Name Type Description Mandatory Default
fun Function An access function that computes comparison keys from the given list elements, which can be used for comparison. yes

Return value

type: Function

A comparison function that can be used for sorting sets and lists.

Examples

Comparison function from an access function

	all(`my.module:MyType`)
  .sort(comparator(x -> $x.get(`my.module:MyType#name`)))

Output: List of all instances of the type my.module:MyType sorted by the values of the attribute name.

Here, the comparator() function makes a comparator function out of the access function x -> $x.get(`my.module:MyType#name`, which returns the value of the property name for a lis element.

Equivalent to the previous example without comparator

	all(`my.module:MyType`)
  .sort(x -> y -> {
    name1 = $x.get(`my.module:MyType#name`);
    name2 = $y.get(`my.module:MyType#name`);
    if ($name1 < $name2, 
      -1, 
      if ($name1 > $name2, 1, 0));
  })

output: List of all instances of the type my.module:MyType sorted by the values of the attribute name.

In the above example, the comparator function is specified directly. Here, the name property must be accessed twice and the (-1, 1, 0) logic of a comparison function is explicitly spelled out. This could also be simplified by using the Comparative value function.