Search code examples
python-3.xclojureiterable-unpacking

Destructuring/Unpacking first and rest in Clojure


In Python 3, if you want to unpack the first and rest of a list (or tuple), you do

x, *y = [1, 2, 3]
#x = 1, y = [2, 3]

How do you do this inside a let block in Clojure? I've tried :as parts and

(defn destructurer [vec]
  (let [[beginning the-rest :as parts] vec]
    [beginning the-rest]
    )
  )
;; (destructer [1 2 3])
;; [1 2] <- missing the 3

Solution

  • You need to add an & to make the next binding capture rest:

    (defn destructurer [vec]
      (let [[beginning & the-rest :as parts] vec]
        [beginning the-rest]
        )
      )
    

    There's a nice github gist on clojure destructuring capabilities here.