t-cool

Common Lisp – destructuring-bind

元の記事はこちらです:

Common Lisp – destructuring-bind / Kyle Burton著

Common Lisp – destructuring-bind

リストの分解

;; これが定番の使い方です。リストを分解します。
(destructuring-bind
      (first second)
    '(1 2)
  (format t "first:~A second:~A ~&" first second))
;;; => first:1 second:2

ドット表記

;; ドット表記のリストも分解できます。
(destructuring-bind
      (first . second)
    '(1 . 2)
  (format t "first:~A second:~A ~&" first second))
;;; => first:1 second:2

ドット表記で残りの引数を全て捕捉

;; destructuring-bindの第一引数はラムダリストですが、
;; ドット記法を使うと、残り全ての引数を捕捉することができます。
(destructuring-bind
      (first second . stuff)
    '(1 2 3 4 5)
  (format t "first:~A second:~A rest:~A ~&" first second stuff))
;;; => first:1 second:2 rest:(3 4 5)

&restで残りの引数を全て捕捉

;; また、レスト引数を使って残り全ての引数を捕捉することもできます。
(destructuring-bind
      (first second &rest stuff)
    '(1 2 3 4 5)
  (format t "first:~A second:~A rest:~A ~&" first second stuff))
;;; => first:1 second:2 rest:(3 4 5)

&optionalでデフォルト値を設定

;; オプショナル引数を使って、引数にデフォルト値を設定することもできます。
(destructuring-bind
      (first second &optional (third 'default))
    '(1 2)
  (format t "first:~A second:~A third:~A ~&" first second third))
;;; => first:1 second:2 third:DEFAULT

(destructuring-bind
      (first second &optional (third 'default))
    '(1 2 3)
  (format t "first:~A second:~A third:~A ~&" first second third))
;;; => first:1 second:2 third:3

キーワード引数の利用

;; また、キーワード引数を使うこともできます。
(destructuring-bind
      (first second &key third)
    '(1 2 :third 3)
  (format t "first:~A second:~A third:~A ~&" first second third))
;;; => first:1 second:2 third:3

木構造を逆パース

;; 最後に、木構造を逆パース(unparse)するためにも使うことができます。
;; 分解したいデータ構造に対して、あなた自身の変数宣言を適用することができます。
;; このテクニックは、XMLをS式に変換した後、データを処理する際に役立ちます。
(destructuring-bind
      (a (b (c d e (f g) h i j)) &rest remainder)
    '(1 (2 (3 4 5 (6 7) 8 9 10)) 11 12 13 14 15)
  (format t
          "a:~A b:~A c:~A d:~A e:~A f:~A g:~A h:~A i:~A j:~A remainder:~A ~&"
          a b c d e f g h i j remainder))
;;; => a:1 b:2 c:3 d:4 e:5 f:6 g:7 h:8 i:9 j:10 remainder:(11 12 13 14 15)