Search code examples
clojuredestructuring

Is is possible to destructure a clojure vector into last two items and the rest?


I know I can destructure a vector "from the front" like this:

(fn [[a b & rest]] (+ a b))

Is there any (short) way to access the last two elements instead?

(fn [[rest & a b]] (+ a b)) ;;Not legal

My current alternative is to

(fn [my-vector] (let [[a b] (take-last 2 my-vector)] (+ a b))) 

and it was trying to figure out if there is way to do that in a more convenient way directly in the function arguments.


Solution

  • You can peel off the last two elements and add them thus:

    ((fn [v] (let [[b a] (rseq v)] (+ a b))) [1 2 3 4])
    ; 7
    
    • rseq supplies a reverse sequence for a vector in quick time.
    • We just destructure its first two elements.
    • We needn't mention the rest of it, which we don't do anything with.