Clojure Goodness: Destructure Sequences
Join the DZone community and get the full member experience.Join For Free
Clojure supports advanced destructure features. In a previous post, we learned about destructuring maps, but we can also destructure vectors, lists, and sequences in Clojure using positional destructuring. We can define symbols for positions in the sequence to assign the value at a certain position to the symbol. The first symbol in the destructure vector gets the value of the first element in the sequence, the second symbol the value of the second element, and so on. To get the remaining elements from the sequence without assigning them to specific symbols we can use
& followed by a symbol. Then all remaining elements are assigned as sequence the symbol. Finally, we can use
:as to get the original vector, list, or sequence.
The following examples show several destructure definitions for different types of collections and sequences:
Written with Clojure 1.10.1.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.