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.
Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)
Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.
When we are unpacking values into variables using tuple unpacking, the number of variables on the left side tuple must exactly match the number of values on the right side tuple . Otherwise, we'll get a ValueError .
Unpack a Tuple in a for Loop in PythonThe number of variables on the left side or before the equals sign should equal the length of the tuple or the list. For example, if a tuple has 5 elements, then the code to unpack it would be as follows. We can use the same syntax to unpack values within a for loop.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With