Sorting by Functions in Clojure

Clojure provides powerful sorting capabilities through its built-in functions. Let’s explore how to implement custom sorting in Clojure.

(ns sorting-by-functions
  (:require [clojure.string :as str]))

(defn main []
  (let [fruits ["peach" "banana" "kiwi"]]
    
    ;; We implement a comparison function for string lengths.
    ;; Clojure's `compare` function is helpful for this.
    (let [len-cmp (fn [a b] (compare (count a) (count b)))]
      
      ;; Now we can use `sort-by` with this custom comparison function
      ;; to sort `fruits` by name length.
      (println (sort-by identity len-cmp fruits)))
    
    ;; We can use the same technique to sort a sequence of
    ;; values that aren't built-in types.
    (let [people [{:name "Jax" :age 37}
                  {:name "TJ" :age 25}
                  {:name "Alex" :age 72}]]
      
      ;; Sort `people` by age using `sort-by`.
      ;; Note: In Clojure, we don't need to worry about the size of the data structure
      ;; as it uses persistent data structures and efficient algorithms.
      (println (sort-by :age people)))))

(main)

This Clojure code demonstrates custom sorting using the sort-by function, which is analogous to Go’s slices.SortFunc. Here’s a breakdown of the differences and similarities:

  1. In Clojure, we don’t need to import a separate package for sorting as it’s part of the core language.

  2. Instead of defining a separate struct for Person, we use Clojure’s built-in map data structure.

  3. The len-cmp function is defined using Clojure’s anonymous function syntax (fn [a b] ...).

  4. Clojure’s sort-by function is used instead of slices.SortFunc. It takes a key function (or keyword) and an optional comparator.

  5. For sorting the people sequence, we simply use :age as the key function, which extracts the age from each person map.

When you run this program, you’ll see output similar to this:

["kiwi" "peach" "banana"]
({:name "TJ", :age 25} {:name "Jax", :age 37} {:name "Alex", :age 72})

This example demonstrates how Clojure’s functional programming paradigm and rich standard library make custom sorting operations concise and expressive.