Vectors & arrays in Lisp
Reads daily temperatures from a #(...) literal and writes into an array built by make-array.
;; #(...) reads as a simple vector, and AREF indexes it from zero.
(defvar *highs* #(61 64 58 72 70))
(defvar *monday* (aref *highs* 0))
(defvar *thursday* (aref *highs* 3))
;; MAKE-ARRAY builds one at run time; :INITIAL-ELEMENT fills it, and
;; SETF AREF writes a slot. Never write into a #(...) literal.
(defvar *lows* (make-array 5 :initial-element 48))
(setf (aref *lows* 3) 55)
;; LENGTH and ELT accept any sequence, so the same call reads a
;; vector, a list, or a string.
(format t "~a days, monday ~a, thursday ~a/~a~%"
(length *highs*) *monday* *thursday* (aref *lows* 3))
(format t "~a ~a ~a~%" (elt *highs* 1) (elt '(:rain :sun) 1)
(elt "cloudy" 0))
How it works
(aref *highs* 3)indexes the literal vector from zero.(make-array 5 :initial-element 48)builds a writable vector that(setf (aref *lows* 3) 55)updates.lengthandeltwork across sequences, so(elt '(:rain :sun) 1)and(elt "cloudy" 0)read a list and a string.
Keywords and builtins used here
arefdefvareltformatlengthsetf
The run, in numbers
- Lines
- 16
- Characters to type
- 662
- Tokens
- 93
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 74 seconds.
Step 3 of 3 in Collections, step 18 of 27 in Language basics.