45 lines
1.7 KiB
Common Lisp
45 lines
1.7 KiB
Common Lisp
;;; SEQUENCES 4: EVERY, SOME, SEARCH, MERGE
|
|
;;;
|
|
;;; EVERY and SOME ask a question of a whole sequence. EVERY wants
|
|
;;; the predicate true of each element - the empty list qualifies.
|
|
;;; SOME settles for one:
|
|
;;; (every #'plusp '(1 2)) => T, (every #'plusp '()) => T
|
|
;;; (some #'minusp '(1 -2)) => T
|
|
;;; SEARCH hunts for a whole subsequence, not one element, and
|
|
;;; returns where it starts, or NIL:
|
|
;;; (search '(b c) '(a b c d)) => 1
|
|
;;; MERGE interleaves two sequences that are already in order, by
|
|
;;; the same kind of comparison SORT takes. Like SORT it may reuse
|
|
;;; its arguments:
|
|
;;; (merge 'list (list 1 3) (list 2 4) #'<) => (1 2 3 4)
|
|
|
|
;; TODO: T when every element of XS satisfies F, NIL otherwise.
|
|
(defun all-fit (f xs)
|
|
(some f xs))
|
|
|
|
;; TODO: The index where NEEDLE starts inside HAY, or NIL.
|
|
(defun needle-at (needle hay)
|
|
(find needle hay))
|
|
|
|
;; TODO: The elements of A and B together, in ascending order. A
|
|
;;; and B arrive already sorted.
|
|
(defun weave (a b)
|
|
(append a b))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal t (all-fit #'plusp '(1 2 3)))
|
|
(check-equal nil (all-fit #'plusp '(-1 2 3)))
|
|
(check-equal t (all-fit #'plusp '()))
|
|
(check (some #'minusp '(1 -2 3)))
|
|
(check-equal 1 (needle-at '(b c) '(a b c d)))
|
|
(check-equal 2 (needle-at '(2 3) '(1 5 2 3)))
|
|
(check-equal 1 (needle-at "ana" "banana"))
|
|
(check-equal nil (needle-at '(9) '(1 2 3)))
|
|
(check-equal '(1 2 3 4) (weave (list 1 3) (list 2 4)))
|
|
(check-equal '(0 1 4 9) (weave (list 4) (list 0 1 9)))
|
|
(check-equal '(2 3) (weave (list 2 3) (list)))
|