What is scheme's equivalent of tuple unpacking?

前端 未结 6 1672
说谎
说谎 2021-02-05 07:39

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

6条回答
  •  别跟我提以往
    2021-02-05 08:17

    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.

提交回复
热议问题