What is scheme's equivalent of tuple unpacking?

前端 未结 6 1676
说谎
说谎 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:02

    Here is a simple destructuring-bind macro for schemes with case-lambda (such as Racket or Chez Scheme):

    (define-syntax bind
       (syntax-rules ()
          ((_ arg pat def body)
             (apply
                (case-lambda
                   [pat body]
                   [x def] )
                arg ))))
    

    Here is the example that motivated me to write this macro. Putting the default before the body makes for readable code:

    (define (permutations l)
       ;
       (define (psub j k y)
          ;
          (define (join a b)
             (bind a (ah . at) b
                (join at (cons ah b)) ))
          ;
          (define (prec a b z)
             (bind b (bh . bt) z
                (prec (cons bh a) bt
                   (psub (cons bh j) (join a bt) z) )))
          ;
          (if (null? k)
             (cons (reverse j) y)
             (prec (list) k y) ))
       ;
       (psub (list) (reverse l) (list)) )
    

    Here are benchmarks for computing permutations of length 9, on various schemes:

    0m0.211s Chez Scheme
    0m0.273s Bigloo
    0m0.403s Chicken
    0m0.598s Racket
    

    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.

提交回复
热议问题