Three-way Comparison - High-level Languages - Composite Data Types

Composite Data Types

Three-way comparisons have the elegant property of being simple to compose to build lexicographic comparisons of non-primitive data types, unlike two-way comparisons.

Here is a composition example in Perl.

sub compare($$) { my ($a, $b) = @_; return $a->{unit} cmp $b->{unit} || $a->{rank} <=> $b->{rank} || $a->{name} cmp $b->{name}; }

Note that cmp is for strings as <=> is for numbers. Two-way equivalents tend to be less compact but not necessarily less legible. The above takes advantage of short-circuit evaluation of the || operator, and the fact that 0 is considered false in Perl. As a result, if the first comparison is equal (thus evaluates to 0), it will "fall through" to the second comparison, and so on., until it finds one that is non-zero, or until it reaches the end.

In some languages, including Python, Ruby, Haskell, etc., comparison of lists are done lexicographically, which means that it is possible to build a chain of comparisons like the above example by putting the values into lists in the order desired; for example in Ruby:

<=>

Read more about this topic:  Three-way Comparison, High-level Languages

Famous quotes containing the words composite, data and/or types:

    A positive learning climate in a school for young children is a composite of many things. It is an attitude that respects children. It is a place where children receive guidance and encouragement from the responsible adults around them. It is an environment where children can experiment and try out new ideas without fear of failure. It is an atmosphere that builds children’s self-confidence so they dare to take risks. It is an environment that nurtures a love of learning.
    Carol B. Hillman (20th century)

    To write it, it took three months; to conceive it three minutes; to collect the data in it—all my life.
    F. Scott Fitzgerald (1896–1940)

    Our major universities are now stuck with an army of pedestrian, toadying careerists, Fifties types who wave around Sixties banners to conceal their record of ruthless, beaverlike tunneling to the top.
    Camille Paglia (b. 1947)