Sorting in Scheme

Scheme’s built-in procedures provide sorting capabilities for lists. We’ll look at sorting for basic data types first.

(define (main)
  ; Sorting functions work for any comparable data type.
  ; For strings, we can use the built-in string-ci<? procedure
  ; for case-insensitive comparison.
  (define strs '("c" "a" "b"))
  (define sorted-strs (sort strs string-ci<?))
  (display "Strings: ")
  (display sorted-strs)
  (newline)

  ; An example of sorting numbers.
  (define nums '(7 2 4))
  (define sorted-nums (sort nums <))
  (display "Numbers: ")
  (display sorted-nums)
  (newline)

  ; We can also check if a list is already in sorted order.
  (define is-sorted? (equal? nums (sort nums <)))
  (display "Sorted: ")
  (display is-sorted?)
  (newline))

(main)

To run the program, save it to a file (e.g., sorting.scm) and use your Scheme interpreter. For example, if you’re using Chez Scheme:

$ chez --script sorting.scm
Strings: (a b c)
Numbers: (2 4 7)
Sorted: #f

In this Scheme example:

  1. We use the built-in sort procedure, which takes a list and a comparison procedure as arguments.

  2. For sorting strings, we use string-ci<? for case-insensitive comparison.

  3. For sorting numbers, we use the standard < procedure.

  4. To check if a list is sorted, we compare the original list with a sorted version of itself using equal?.

Note that unlike Go’s slice operations which modify the original slice, Scheme’s sort returns a new sorted list, leaving the original list unchanged. This is more in line with Scheme’s functional programming paradigm.

Also, Scheme doesn’t have a built-in IsSorted function, so we implement this functionality by comparing the original list with its sorted version.

Remember that the exact syntax and available procedures may vary slightly depending on the Scheme implementation you’re using.