Sorting By Functions in Lisp
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Lisp.
We start by defining a comparison function len-cmp
that compares the lengths of two strings. In Lisp, we can directly subtract the lengths to get the comparison result.
In the main
function, we first demonstrate sorting a list of fruits by their length. We use the sort
function, which takes a sequence and a predicate function. Our len-cmp
function serves as this predicate.
Next, we show how to sort custom structures. We define a person
struct with name
and age
fields. We create a list of person
instances and then sort them by age. For this, we use an anonymous function (lambda) as our sorting predicate, which compares the age
fields of two person
instances.
To run the program, save it to a file (e.g., sorting-by-functions.lisp
) and use your Lisp interpreter. For example, if you’re using SBCL:
This example demonstrates how Lisp’s flexible function handling allows for easy implementation of custom sorting logic, both for built-in types and user-defined structures.