42 lines
1.3 KiB
Common Lisp
42 lines
1.3 KiB
Common Lisp
;;; VECTORS 3: STRINGS ARE VECTORS
|
|
;;;
|
|
;;; A string is a vector of characters, so the vector tools work on
|
|
;;; it unchanged. #\a is the character a.
|
|
;;; (aref "cat" 0) => #\c
|
|
;;; (length "cat") => 3
|
|
;;; (vectorp "cat") => T
|
|
;;; MAKE-ARRAY with :element-type 'character builds strings:
|
|
;;; (make-array 3 :element-type 'character :initial-element #\a)
|
|
;;; => "aaa"
|
|
;;; To change a string, work on your own copy: MAKE-ARRAY with
|
|
;;; :initial-contents duplicates an existing one.
|
|
|
|
;; TODO: The first character of the word W.
|
|
(defun first-letter (w)
|
|
(aref w 1))
|
|
|
|
;; TODO: W with its last character replaced by C. Leave the caller's
|
|
;;; string alone: build a copy first.
|
|
(defun retag (w c)
|
|
w)
|
|
|
|
;; TODO: A fresh string of N copies of the character C.
|
|
(defun letter-run (n c)
|
|
(make-array n))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check (vectorp "cat"))
|
|
(check-equal #\c (first-letter "cat"))
|
|
(check-equal #\a (first-letter "apple"))
|
|
(check-equal "cab" (retag "cat" #\b))
|
|
(check-equal "suns" (retag "sung" #\s))
|
|
(check (let ((w "cat"))
|
|
(retag w #\b)
|
|
(equal "cat" w)))
|
|
(check-equal "aaa" (letter-run 3 #\a))
|
|
(check-equal "xx" (letter-run 2 #\x))
|