Now, the one very important thing I remembered:
(let [[a b c :as d] [1 2 3]] (println a b c d))
results in
1 2 3 [1 2 3]
You can use :as in both vector and map destructuring.
The second thing... I tried it on a hunch, really.
In a very abstracted sense, you can treat vectors as maps with ordered integer keys.
So, a function I wrote got input in the form of a seq (the general sequence datatype of Clojure) of vectors. The vectors contained three elements each, but the only one I needed was the second one (index 1, in other words).
So I tried this...
(let [{thing 1} hypothetical-3-element-vector]
(println thing))
Now, assuming hypothetical-3-element-vector is bound to, say [1 "lol" 2], the result will be...
lol
So not only can YOU hypothetically treat vectors that way, Clojure does so. In a way.
It probably isn't very useful that often, but still a neat thing to know.
[Edit; Afterthoughts resulting from a walk with my dogs:]
Now that I think of it, this implies that destructuring, under the hood, uses get (or at least a similar mechanic). get handles both vectors and maps gracefully (which neatly extends to get-in... on which I rely a lot.)
So... I consulted The Joy of Clojure (get this book.). Apparently, there is so much more awesomeness hidden in destructuring. But won't discuss it here/now. Sadly it doesn't reveal anything about the inner workings, though. Will need to search later.
No comments:
Post a Comment