Can you destructure a function parameter but still have the original available for use? The way I'm doing it now is just using a let
form inside the function body, but I wondering if there was a terser way of doing it.
Asked
Active
Viewed 1.1k times
26

noahlz
- 10,202
- 7
- 56
- 75

Ilia Choly
- 18,070
- 14
- 92
- 160
1 Answers
33
Seems like :as
works for functions too:
with vector
(defn test [[x y :as v]]
{:x x :y y :v v})
(test [1 2 3 4])
=> {:x 1 :y 2 :v [1 2 3 4]}
with hash-map
(defn test2 [{x :x y :y :as m}]
{:x x :y y :m m})
(test2 {:x 1 :y 2 :z 3})
=> {:x 1 :y 2 :m {:x 1 :y 2 :z 3}}
See this terrific blog post: http://blog.jayfields.com/2010/07/clojure-destructuring.html

Ilia Choly
- 18,070
- 14
- 92
- 160

noahlz
- 10,202
- 7
- 56
- 75
-
4I believe let, fn, defn, etc. all use the same destructuring syntax. – JohnJ Sep 25 '12 at 03:21
-
1@JohnJ That's "true". I was very confused at the blog post at first because it only uses lets as examples. The difference between the let and the fn/defn is that it uses a binding form. – Daniel Kaplan Apr 02 '13 at 21:38
-
2Everything what uses `let` internally can be destructured in the same way. – Adam Arold Jan 26 '14 at 00:15