Jas*_*ker 17 scheme list racket iterable-unpacking
在Python中,我可以这样做:
t = (1, 2)
a, b = t
Run Code Online (Sandbox Code Playgroud)
......并且a将为1,b将为2.假设我'(1 2)在Scheme中有一个列表.有没有办法做类似的事情let?如果它有所作为,我正在使用Racket.
Eli*_*lay 26
在球拍,你可以使用match,
(define t (list 1 2))
(match [(list a b) (+ a b)])
Run Code Online (Sandbox Code Playgroud)
以及相关的事情match-define:
(match-define (list a b) (list 1 2))
Run Code Online (Sandbox Code Playgroud)
(match-let ([(list a b) t]) (+ a b))
Run Code Online (Sandbox Code Playgroud)
这适用于列表,向量,结构等.对于多个值,您可以使用define-values:
(define (t) (values 1 2))
(define-values (a b) (t))
Run Code Online (Sandbox Code Playgroud)
或let-values.但请注意,我不能将其定义t为"元组",因为多个值不是(大多数)方案实现中的第一类值.
裸骨成语是使用申请与拉姆达在那里你会使用让,如:
(define t '(1 2))
(apply (lambda (a b)
;; code that would go inside let
)
t)
Run Code Online (Sandbox Code Playgroud)
优点是它适用于任何实现.当然,这只能用于简单的情况,但有时这就是你所需要的.
您正在寻找的内容(至少在Lisp-world中)的一般术语是解构,实现它的宏称为destructuring-bind.在Common Lisp中,它的工作原理如下:
(destructuring-bind (a b c) '(1 2 3)
(list a b c)) ;; (1 2 3)
Run Code Online (Sandbox Code Playgroud)
它也适用于嵌套的多个"级别":
(destructuring-bind (a (b c) d) '(1 (2 3) 4)
(list a b c d)) ;; (1 2 3 4)
Run Code Online (Sandbox Code Playgroud)
看起来有一个很好的destructuring-bind实现作为一个方案宏.