38 lines
1.3 KiB
Common Lisp
38 lines
1.3 KiB
Common Lisp
;;; SEQUENCES 1: FIND, POSITION, COUNT
|
|
;;;
|
|
;;; A sequence is anything you can walk element by element: a list,
|
|
;;; a vector, a string. One toolbox serves them all.
|
|
;;; (find 2 '(1 2 3)) => 2 the element itself, or NIL
|
|
;;; (position 2 #(1 2 3)) => 1 where it sits, or NIL
|
|
;;; (count 'a '(a b a)) => 2 how many match
|
|
;;; :test decides what counts as a match. The default, EQL, treats
|
|
;;; 1 and 1.0 as different numbers; #'= does not.
|
|
|
|
;; TODO: The index where X sits in XS, or NIL.
|
|
(defun index-of (x xs)
|
|
(find x xs))
|
|
|
|
;; TODO: How many times X occurs in XS.
|
|
(defun occurrences (x xs)
|
|
(position x xs))
|
|
|
|
;; TODO: The first element of XS numerically equal to X, so that
|
|
;;; 1.0 can find the integer 1.
|
|
(defun find-same (x xs)
|
|
(find x xs))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal 1 (index-of 'b #(a b c)))
|
|
(check-equal 2 (index-of 3 '(1 2 3)))
|
|
(check-equal nil (index-of 9 '(1 2 3)))
|
|
(check-equal 3 (occurrences 'a #(a b a c a)))
|
|
(check-equal 2 (occurrences 'b '(a b a b a)))
|
|
(check-equal 0 (occurrences 5 '(1 2 3)))
|
|
(check-equal 1 (find-same 1.0 '(2 1 3)))
|
|
(check-equal 2 (find-same 2.0 '(1 2 3)))
|
|
(check-equal nil (find-same 9 '(1 2 3)))
|