Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is scheme's equivalent of tuple unpacking?

Tags:

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.

like image 905
Jason Baker Avatar asked Nov 18 '10 22:11

Jason Baker


People also ask

What is unpacking of a tuple?

Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)

What is tuple packing and unpacking?

Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.

How does tuple unpacking work in Python?

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 .

How do I unpack a tuple in a for loop?

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.


1 Answers

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.

like image 59
Eli Barzilay Avatar answered Oct 13 '22 23:10

Eli Barzilay