実践CommonLisp:スカラー・コレクション
スカラー
スカラーなデータ型・・・数、文字、文字列。
数
読取器は正規化してオブジェクトに変換する
CL-USER> 10 10 CL-USER> 20/5 4 CL-USER> #xa 10
#bは二進数
#oは八進数
#xは十六進数
#cは複素数
実数の切り捨て/丸め
CL-USER> (setf lis '(10.49 10.50 10.51)) (10.49 10.5 10.51) CL-USER> (mapcar #'floor lis) (10 10 10) CL-USER> (mapcar #'ceiling lis) (11 11 11) CL-USER> (mapcar #'truncate lis) (10 10 10) CL-USER> (mapcar #'round lis) (10 10 11)
割り算における法、および剰余:mod
CL-USER> (mod 10 3) 1
数値比較:zerop,minusp,plusp,evenp,oddp
文字
"#\"の後に文字を続ける
CL-USER> #\a #\a CL-USER> #\Space #\Space
文字列
複合データ型
CL-USER> "foobar" "foobar" CL-USER> (elt "foobar" 3) #\b CL-USER> (string= "foobar" "foobar") T CL-USER> (eql "foobar" "foobar") NIL
コレクション
ベクタ
生成。
CL-USER> (vector 1 2 3) #(1 2 3) CL-USER> (make-array 3 :initial-element T) #(T T T) CL-USER> (make-array 3 :fill-pointer 0) #() CL-USER> (setf arr (make-array 3 :fill-pointer 0)) #() CL-USER> (vector-push 'a arr) 0 CL-USER> arr #(A) CL-USER> (vector-pop arr) A CL-USER> arr #()
シーケンス
ベクタもリストも、シーケンスという抽象的な型のサブタイプ。
シーケンスの反復。
CL-USER> (setf x (vector 1 2 3 4 5)) #(1 2 3 4 5) CL-USER> (find 2 x) 2 CL-USER> (remove 2 x) #(1 3 4 5) CL-USER> (position 2 x) 1 CL-USER> (count 2 x) 1 CL-USER> (substitute 2 x) ; Evaluation aborted. CL-USER> (substitute 2 1 x) #(2 2 3 4 5)
シーケンスの高階関数。
CL-USER> (count-if #'oddp x) 3 CL-USER> (find-if #'oddp x) 1 CL-USER> (remove-if #'oddp x) #(2 4) CL-USER> (position-if #'oddp x) 0 CL-USER> (substitute-if 5 #'oddp x) #(5 2 5 4 5)
シーケンス全体操作。
CL-USER> (concatenate 'list x) (1 2 3 4 5) CL-USER> (concatenate 'vector x) #(1 2 3 4 5) CL-USER> (copy-seq x) #(1 2 3 4 5) CL-USER> (reverse x) #(5 4 3 2 1)
ソート。破壊的関数。
CL-USER> (sort x #'>) #(5 4 3 2 1) CL-USER> x #(5 4 3 2 1)
マージ。
CL-USER> (merge 'vector x x #'>) #(5 5 4 4 3 3 2 2 1 1)
部分シーケンス。
CL-USER> (subseq x 3) #(2 1)
述語。
CL-USER> (every #'oddp x) NIL CL-USER> (some #'oddp x) T CL-USER> (notany #'oddp x) NIL CL-USER> (notevery #'oddp x) T
シーケンスマッピング関数。
CL-USER> (map 'vector #'* x x) #(25 16 9 4 1) CL-USER> (map-into x #'+ x x) #(10 8 6 4 2) CL-USER> x #(10 8 6 4 2) CL-USER> (reduce #'+ x) 30
ハッシュテーブル
CL-USER> (setf hash (make-hash-table)) #S(HASH-TABLE :TEST FASTHASH-EQL) CL-USER> (gethash 'foo hash) NIL NIL CL-USER> (setf (gethash 'foo hash) 'a) A CL-USER> (gethash 'foo hash) A T
多値を扱う場合は、multiple-value-bindを使う。
CL-USER> (multiple-value-bind (value present) (gethash 'foo hash) (if present (format nil "hit:~a" value) (format nil "not found" value))) "hit:A" CL-USER> (multiple-value-bind (value present) (gethash 'bar hash) (if present (format nil "hit:~a" value) (format nil "not found" value))) "not found"
ハッシュテーブルの反復。
CL-USER> (maphash #'(lambda (k v) (format t "~a:~a" k v)) hash) FOO:A NIL