liveBook · Manning

Comparison function

A comparison function or strategy compares two values and indicates their relative ordering, and sometimes whether they are equivalent.

How 3 Manning books explain it

Clojure: The Essential Reference

The Java Comparator interface defines an object contract for comparing two values through a compare method.

How it is used
Orders values for sorting and for sorted maps and sets, with custom comparisons when default ordering is unsuitable.
How deep it goes
Defines the three-way result, works through custom ordering and tie-breakers, and identifies incompatible inputs and NaN behavior.
Examples
Uses reversed string ordering, equal-length vector collisions, and vector tie-breakers to demonstrate comparator behavior.
What you can do after
Apply it via sorted-map-by and sorted-set-by to choose an order without unintentionally collapsing distinct keys or elements.

Read how Clojure: The Essential Reference explains comparison function →

Modern C, Third Edition

A comparison function is a caller-supplied function that determines the ordering or equality of two data elements for an algorithm such as sorting or searching.

How it is used
Deploys comparison functions as callbacks that give qsort and bsearch an ordering for otherwise type-generic data.
How deep it goes
Explains the callback contract, void-pointer conversions, overflow hazard, and sortedness requirement without developing ordering theory further.
Examples
Uses unsigned comparison code, an invalid subtractive integer comparator, and qsort or bsearch interfaces.
What you can do after
Apply qsort and bsearch with comparison callbacks that preserve element types, ordering results, overflow safety, and sortedness.

Read how Modern C, Third Edition explains comparison function →

Modern C

A comparison function is a callback that determines the ordering of two values by returning a negative, zero, or positive result.

How it is used
Deploys callbacks to give qsort and bsearch type-independent ordering information for array elements.
How deep it goes
Explains the return contract, void-pointer conversions, and integer-overflow pitfall, but defers a complete search or sorting implementation.
Examples
Uses unsigned comparison code, an overflowing integer subtraction comparator, and qsort/bsearch declarations.
What you can do after
Apply it via qsort and bsearch by writing a consistent comparator and supplying the correct element size.

Read how Modern C explains comparison function →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.