39 lines
1.5 KiB
Common Lisp
39 lines
1.5 KiB
Common Lisp
;;; SEQUENCES 3: SORT, :KEY, REVERSE
|
|
;;;
|
|
;;; SORT arranges a sequence by a comparison function:
|
|
;;; (sort (list 3 1 2) #'<) => (1 2 3)
|
|
;;; SORT is allowed to rearrange the very sequence you hand it, so
|
|
;;; pass it a fresh one - the checks below all build with LIST.
|
|
;;; :key picks out the part to compare:
|
|
;;; (sort pairs #'< :key #'cdr) sorts by each pair's price
|
|
;;; REVERSE returns a backwards copy, and its input stays as it
|
|
;;; was: (reverse '(1 2 3)) => (3 2 1)
|
|
|
|
;; TODO: XS from smallest to largest.
|
|
(defun ascending (xs)
|
|
(sort xs #'>))
|
|
|
|
;; TODO: ALIST, a list of (item . price) pairs, sorted cheapest
|
|
;;; first.
|
|
(defun by-price (alist)
|
|
(sort alist #'< :key #'car))
|
|
|
|
;; TODO: Each word of XS reversed, with the words still in order.
|
|
(defun back-words (xs)
|
|
(reverse xs))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal '(1 2 3) (ascending (list 3 1 2)))
|
|
(check-equal '(-1 0 4) (ascending (list 4 0 -1)))
|
|
(check-equal '(3 2 1) (reverse (list 1 2 3)))
|
|
(check-equal '((tea . 1) (cola . 2))
|
|
(by-price (list (cons 'cola 2) (cons 'tea 1))))
|
|
(check-equal '((b . 1) (c . 2) (a . 7))
|
|
(by-price (list (cons 'a 7) (cons 'b 1) (cons 'c 2))))
|
|
(check-equal '("tac" "esaelp") (back-words '("cat" "please")))
|
|
(check-equal '("bba" "aa") (back-words '("abb" "aa")))
|