Sorting in Clojure

Our example demonstrates sorting in Clojure. We’ll look at sorting for built-in types first.

(ns sorting-example
  (:require [clojure.core.protocols :as protocols]))

(defn main []
  ;; Sorting functions in Clojure work for any collection of
  ;; comparable elements.
  (let [strs ["c" "a" "b"]]
    (println "Strings:" (sort strs)))

  ;; An example of sorting numbers.
  (let [nums [7 2 4]]
    (println "Numbers:" (sort nums)))

  ;; We can also check if a sequence is already in sorted order.
  (let [nums [2 4 7]]
    (println "Sorted:" (protocols/sorted? nums))))

(main)

In Clojure, sorting is primarily done using the sort function, which works on any collection of comparable elements. The sorted? function from the clojure.core.protocols namespace can be used to check if a sequence is already sorted.

To run the program, save it in a file (e.g., sorting_example.clj) and use the Clojure CLI or REPL to execute it.

$ clj sorting_example.clj
Strings: ("a" "b" "c")
Numbers: (2 4 7)
Sorted: true

Clojure’s sorting functions are powerful and flexible. They work with various data structures and can be customized with comparator functions for more complex sorting scenarios.

查看推荐产品

Comments powered by Disqus