In Python, I can do something like this:
t = (1, 2)
a, b = t
...and a will be 1 and b will be 2. Suppose I have a list '(1 2)
in Scheme. Is there any way to do something similar with let
? If it makes a difference, I'm using Racket.
In Python, I can do something like this:
t = (1, 2)
a, b = t
...and a will be 1 and b will be 2. Suppose I have a list '(1 2)
in Scheme. Is there any way to do something similar with let
? If it makes a difference, I'm using Racket.
This works in Racket if you don't want to bring in the
match
dependency:From a list:
Or directly from a values expression:
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:
it also works for multiple "levels" of nesting:
It looks like there's a nice implementation of destructuring-bind as a scheme macro.
In racket you can use
match
,and related things like
match-define
:and
match-let
That works for lists, vectors, structs, etc etc. For multiple values, you'd use
define-values
:or
let-values
. But note that I can't definet
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:
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.
I think this is what you are looking for:
Look at
let-values
orlet+
.Here is a simple
destructuring-bind
macro for schemes withcase-lambda
(such as Racket or Chez Scheme):Here is the example that motivated me to write this macro. Putting the default before the body makes for readable code:
Here are benchmarks for computing permutations of length 9, on various schemes:
The translation to GHC Haskell is 5x faster than Chez Scheme. Guile is much slower than any of these schemes.
Aside from the ease of leveraging the existing
case-lambda
code, I like how this macro accepts exactly the same syntax as function definition argument lists. I love the simplicity of scheme. I'm old enough to remember programming Fortran on punched cards, where the allowed syntax varied wildly with context. Scheme is supposed to be better than that. The impulse is overwhelming to guild the lily on macros like this. If you can't justify changing the syntax for function definitions too, then don't change that syntax here either. Having an orthogonal grammar is important.