Sorting By Functions in Scheme
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 Scheme.
To run the program, save it to a file (e.g., sorting-by-functions.scm
) and use your Scheme interpreter. For example, if you’re using Chez Scheme:
In this Scheme version:
We define a list of fruits and a custom comparison function
len-cmp
to compare string lengths.We use the
sort
function (which is part of the R7RS Scheme standard) with our custom comparison function to sort the fruits by length.We define a
<person>
record type to represent people with names and ages.We create a list of
<person>
records and define another custom comparison functionage-cmp
to compare ages.We sort the list of people using
sort
with ourage-cmp
function.Finally, we display the sorted results.
Note that the exact implementation might vary slightly depending on your Scheme implementation, as some functions (like sort
) are not part of the minimal R5RS standard and their availability or exact usage might differ.