试着整理了 Emacs (25) 中能用来 Destructuring binding 的工具:
Library | API | Scope |
---|---|---|
cl-lib | cl-destructuring-bind |
List |
pcase |
pcase , pcase-let
|
List, Vector, Etc |
seq | seq-let |
List, Vector, String |
let-alist | let-alist |
Alist |
map | map-let |
Alist, Hash Table, Vector |
以上都是 Emacs 25 自带,可以从所支持的数据类型 (List, Alist, Hash-Table 等) 这个角度比较它们。
1. cl-destructuring-bind
(List)
(cl-destructuring-bind (x y) '(1 2)
(list x y))
;; => (1 2)
(cl-destructuring-bind ((k1 . v1) (k2 . v2)) '((:one . 1) (:two . 2) )
(list k1 v1 k2 v2))
;; => (:one 1 :two 2)
(cl-destructuring-bind (k1 v1 k2 v2) '(:one 1 :two 2)
(list k1 v1 k2 v2))
;; => (:one 1 :two 2)
2. pcase-let
(List, Vector, Etc)
(pcase-let ((`(,x ,y)
'(1 2)))
(list x y))
;; => (1 2)
(pcase-let ((`((,k1 . ,v1) (,k2 . ,v2))
'((:one . 1) (:two . 2))))
(list k1 v1 k2 v2))
;; => (:one 1 :two 2)
(pcase-let ((`(,k1 ,v1 ,k2 ,v2)
'(:one 1 :two 2)))
(list k1 v1 k2 v2))
;; => (:one 1 :two 2)
(pcase-let ((`[,x ,y] '[1 2]))
(list x y))
;; => (1 2)
3. seq-let
(List, Vector, String)
(seq-let (x y) '(1 2)
(list x y))
;; => (1 2)
(seq-let [x y] [1 2]
(list x y))
;; => (1 2)
(seq-let [x y] "Hello World"
(string x y))
;; => "He"
(seq-let ((k1 . v1) (k2 . v2)) '((:one . 1) (:two . 2))
(list k1 v1 k2 v2))
;; error-> Wrong type argument: listp, v1
;; 不支持
(seq-let ((x y)) '((1 2))
(list x y))
;; => (1 2)
4. let-alist
(Alist)
(let-alist '((one . 1) (two . 2))
(list .one .two))
;; => (1 2)
5. map-let
(Alist, Hash Table & Array)
(map-let (one two) '((one . 1) (two . 2))
(list one two))
;; => (1 2)
(map-let ((:one one) (:two two)) '((:one . 1) (:two . 2))
(list one two))
;; => (1 2)
(map-let (one two) #s(hash-table data (one 1 two 2 three 3))
(list one two))
;; => (1 2)
(map-let ((1 one) (99 ninety-nine)) (vconcat (number-sequence 0 100))
(list one ninety-nine))
;; => (1 99)