Clojure's Associative Destructuring allows one to destructure a vector, (and maybe a seq or list) by numeric index.
This pattern is not mentioned at clojure.org so far, but is mentioned in the The Joy of Clojure, 2nd ed. Michael Fogus, Chris Houser, May 2014, p. 59. There this approach appears in a section called "Associative Destructuring" - wrongly as this index-based destructuring this is just a special case of "Associative Destructuring", which in said book, is called "Destructuring with a map" instead.
Anyway, the results are unexpected (Clojure 1.10.0):
In all cases, extract values at index 0 and 3.
These work as expected:
(let [{firstthing 0, lastthing 3} [1 2 3 4]] [firstthing lastthing])
;=> [1 4]
(let [{firstthing 0, lastthing 3} (vec '(1 2 3 4))] [firstthing lastthing])
;=> [1 4]
But on a list:
(let [{firstthing 0, lastthing 3} '(1 2 3 4)] [firstthing lastthing])
;=> [nil 4]
Why is there nil
at position 0?
Similarly:
(let [{firstthing 0, lastthing 3} (seq '(1 2 3 4))] [firstthing lastthing])
;=> [nil 4]
But on the other hand:
(let [{firstthing 0, lastthing 3} (vec (seq '(1 2 3 4)))] [firstthing lastthing])
;=> [1 4]
What's going on here?
Addendum:
(let [{firstthing 0, lastthing 3} { 1 2 3 4 } ] [firstthing lastthing])
;=> [nil 4]
... sounds reasonable as the map to be associatively destructed is actually {1 2, 3 4}
. So the result of a lookup, not by position but by integer key (changing the meaning of the expression underneath our feet, so to say) would exactly be [nil 4]
. Is anything that is not a vector poured into a map first?
(let [{firstthing 10, lastthing 30} (seq '(10 2 30 4))] [firstthing lastthing])
;=> [2 4]
It certainly looks like it....
(let [{firstthing 10, lastthing 30} (seq '(10 2 30 ))] [firstthing lastthing])
; Execution error (IllegalArgumentException) at user/eval367 (REPL:1).
; No value supplied for key: 30
Oh yeah.
(map associative? [{} [] ()])
:(true true false)
.