49 lines
1.8 KiB
Common Lisp
49 lines
1.8 KiB
Common Lisp
;;; VECTORS 2: FILL POINTERS AND GROWING VECTORS
|
|
;;;
|
|
;;; A vector can carry a fill pointer: the number of slots in use.
|
|
;;; VECTOR-PUSH stores a value past it and returns the slot index;
|
|
;;; on a full vector it returns NIL instead.
|
|
;;; (make-array 4 :fill-pointer 0) => empty, with room for 4
|
|
;;; (fill-pointer v) => slots in use
|
|
;;; (vector-push 'x v) => 0, the index it landed on
|
|
;;; VECTOR-PUSH-EXTEND grows the vector itself when it fills up, so
|
|
;;; the vector must be made :adjustable:
|
|
;;; (make-array 2 :fill-pointer 2 :adjustable t)
|
|
|
|
;; TODO: A vector with room for ROOM items, none in use yet.
|
|
(defun blank-row (room)
|
|
(make-array room))
|
|
|
|
;; TODO: Push X onto V three times, then return V.
|
|
(defun triple-push (v x)
|
|
v)
|
|
|
|
;; TODO: A fresh growable vector holding A and B.
|
|
(defun growable (a b)
|
|
(make-array 2 :initial-contents (list a b) :fill-pointer 2))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal 0 (fill-pointer (blank-row 4)))
|
|
(check-equal 0 (vector-push 'z (blank-row 5)))
|
|
(check (let ((v (blank-row 3)))
|
|
(vector-push 'a v)
|
|
(equal 1 (fill-pointer v))))
|
|
(check-equal nil (vector-push 'x (make-array 2 :fill-pointer 2)))
|
|
(check-error (fill-pointer (make-array 3)))
|
|
(check-equal 3
|
|
(fill-pointer (triple-push (make-array 3 :fill-pointer 0)
|
|
'q)))
|
|
(check-equal 'q
|
|
(aref (triple-push (make-array 3 :fill-pointer 0) 'q)
|
|
2))
|
|
(check (let ((v (growable 'a 'b)))
|
|
(vector-push-extend 'c v)
|
|
(equal 'c (aref v 2))))
|
|
(check (let ((v (growable 1 2)))
|
|
(vector-push-extend 9 v)
|
|
(equal 9 (aref v 2))))
|