Arc Forumnew | comments | leaders | submitlogin
Pattern matching on lists in let
6 points by noahlt 6133 days ago | 3 comments
Not sure if this is documented:

  (let (x y . z) '(a b c d)
    (do (prn "x -> " x)
        (prn "y -> " y)
        (prn "z -> " z)))
  x -> a
  y -> b
  z -> (c d)
Very cool, like Python's tuple unpacking.


4 points by simonb 6133 days ago | link

Since what let does is create a closure, it will swallow anything a lambda-list will. You can for instance use optional arguments:

  (let (foo baz (o bar 3)) '(1 2)
    (+ foo baz bar))
This also means you can't bind symbol "o" to the first value of a list being destructured:

  (let (foo baz (o bar)) '(1 2 (3 4))
    (+ foo baz bar o))
  Error: "reference to undefined identifier: _o"

-----

2 points by ryszard_szopa 6133 days ago | link

Heh, not being able to bind to o by destructuring doesn't look like an intended behavior... Anyway, using `o' in order to mark optional arguments looked suspicious from the beginning. And now we know why.

-----

2 points by ryszard_szopa 6133 days ago | link

It can do even more complicated things:

(let (x (y (w)) z) (list 1 '(2 (2.5)) 3)

     (do (prn "x: " x)

	 (prn "x: " x)

	 (prn "w: " w)

         (prn "z: " z)))
x: 1

x: 1

w: 2.5

z: 3

-----