Files

34 lines
1.3 KiB
Common Lisp

;;; SEQUENCES 2: REMOVE, REMOVE-IF, SUBSTITUTE
;;;
;;; All three return a fresh sequence and leave their input alone.
;;; REMOVE drops the matches; REMOVE-IF drops everything its
;;; predicate accepts; SUBSTITUTE swaps every match for a new
;;; element, reading its arguments as NEW, OLD, then the sequence.
;;; (remove 'b '(a b c b)) => (A C)
;;; (remove-if #'minusp '(-1 0 2)) => (0 2)
;;; (substitute 'x 1 '(1 2 1)) => (X 2 X)
;; TODO: XS with every occurrence of X dropped.
(defun drop-them (x xs)
(remove xs x))
;; TODO: XS with every negative number removed.
(defun drop-negatives (xs)
(remove-if #'plusp xs))
;; TODO: XS with every occurrence of OLD replaced by NEW.
(defun swap-them (new old xs)
(substitute old new xs))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(a c) (drop-them 'b '(a b c b)))
(check-equal '(1 3) (drop-them 2 '(2 1 2 3 2)))
(check-equal '(1 0 2) (drop-negatives '(-1 1 0 -2 2)))
(check-equal '(3) (drop-negatives '(-5 -3 3)))
(check-equal '(x 2 x) (swap-them 'x 1 '(1 2 1)))
(check-equal '(a b a) (swap-them 'a 'z '(z b z)))