What is scheme's equivalent of tuple unpacking?

In racket you can use match,

(define t (list 1 2))
(match [(list a b) (+ a b)])

and related things like match-define:

(match-define (list a b) (list 1 2))

and match-let

(match-let ([(list a b) t]) (+ a b))

That works for lists, vectors, structs, etc etc. For multiple values, you'd use define-values:

(define (t) (values 1 2))
(define-values (a b) (t))

or let-values. But note that I can't define t as a "tuple" since multiple values are not first class values in (most) scheme implementations.


A bare-bones idiom is to use apply with lambda where you'd use let, like:

(define t '(1 2))
(apply (lambda (a b)
          ;; code that would go inside let
        )
        t)

The advantage is that it works on any implementation. Of course this can only be used on simple cases, but sometimes that's all you need.


The general term for what you're looking for (at least in Lisp-world) is destructuring and a macro that implements it is known as destructuring-bind. In Common Lisp, it works like this:

(destructuring-bind (a b c) '(1 2 3)
  (list a b c)) ;; (1 2 3)

it also works for multiple "levels" of nesting:

(destructuring-bind (a (b c) d) '(1 (2 3) 4)
  (list a b c d)) ;; (1 2 3 4)

It looks like there's a nice implementation of destructuring-bind as a scheme macro.