Sorting By Functions in Racket

Our example demonstrates custom sorting in Racket. We’ll sort strings by their length and also sort a list of custom structures.

#lang racket

(require racket/sort)

(define fruits '("peach" "banana" "kiwi"))

; We implement a comparison function for string lengths.
(define (len-cmp a b)
  (< (string-length a) (string-length b)))

; Now we can use sort with this custom comparison function
; to sort 'fruits' by name length.
(displayln (sort fruits len-cmp))

; We can use the same technique to sort a list of
; values that aren't built-in types.
(struct person (name age))

(define people
  (list (person "Jax" 37)
        (person "TJ" 25)
        (person "Alex" 72)))

; Sort 'people' by age using sort with a custom comparison function.
(displayln
 (sort people
       (λ (a b)
         (< (person-age a) (person-age b)))))

In this Racket code:

  1. We start by importing the racket/sort module which provides sorting functions.

  2. We define a list of fruits and a custom comparison function len-cmp that compares strings based on their length.

  3. We use the sort function with our custom comparison function to sort the fruits by length.

  4. We define a person struct to represent people with names and ages.

  5. We create a list of person structs.

  6. We use sort again with a lambda function that compares person structs by their age to sort the list of people.

To run this program, save it as sorting-by-functions.rkt and use the Racket interpreter:

$ racket sorting-by-functions.rkt
(kiwi peach banana)
(#<person> #<person> #<person>)

Note that Racket’s struct printer doesn’t show the contents of the structs by default. If you want to see the sorted data, you might need to implement a custom printing function or use struct-out when defining the struct.

This example demonstrates how Racket’s sorting functions can be customized with comparison functions, allowing for flexible sorting of both built-in and custom data types.