Sorting in Lisp
Our example demonstrates sorting in Lisp. We’ll look at sorting for built-in types first.
(defun main ()
;; Sorting functions in Lisp work for any sequence type that can be compared.
;; Here's an example of sorting strings:
(let ((strs '("c" "a" "b")))
(setq strs (sort strs #'string<))
(format t "Strings: ~a~%" strs))
;; An example of sorting integers:
(let ((ints '(7 2 4)))
(setq ints (sort ints #'<))
(format t "Ints: ~a~%" ints))
;; We can also check if a list is already in sorted order.
(let ((sorted (equal ints (sort (copy-list ints) #'<))))
(format t "Sorted: ~a~%" sorted)))
(main)
In Lisp, we use the sort
function to sort sequences. The sort
function takes two arguments: the sequence to be sorted and a comparison function.
For strings, we use #'string<
as the comparison function, which compares strings lexicographically. For integers, we use #'<
, which compares numbers.
To check if a list is sorted, we can compare the original list with a sorted copy of itself. We use copy-list
to create a copy before sorting to avoid modifying the original list.
Note that sort
in Lisp modifies the original sequence. If you want to preserve the original, you should make a copy before sorting.
When you run this program, you should see output similar to this:
Strings: (A B C)
Ints: (2 4 7)
Sorted: T
This demonstrates basic sorting operations in Lisp. The language provides powerful and flexible sorting capabilities that can be customized for various data types and sorting criteria.