Is it possible to destroy the clojure vector in the last two elements, and the rest?

I know that I can destroy the vector "from the front" as follows:

(fn [[ab & rest]] (+ ab)) 

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

 (fn [[rest & ab]] (+ ab)) ;;Not legal 

My current alternative is

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

and he was trying to figure out if there is a way to do this in a more convenient way directly in function arguments.

+6
source share
2 answers

You can remove the last two elements and add them this way:

 ((fn [v] (let [[ba] (rseq v)] (+ ab))) [1 2 3 4]) ; 7 
  • rseq quickly provides the reverse sequence for a vector.
  • We simply destroy the first two elements.
  • We do not need to mention the rest of which we do nothing.
+9
source
 user=> (def v (vec (range 0 10000000))) #'user/v user=> (time ((fn [my-vector] (let [[ab] (take-last 2 my-vector)] (+ ab))) v)) "Elapsed time: 482.965121 msecs" 19999997 user=> (time ((fn [my-vector] (let [a (peek my-vector) b (peek (pop my-vector))] (+ ab))) v)) "Elapsed time: 0.175539 msecs" 19999997 

My advice would be to use convenience for the wind and use peek and pop to work with the end of the vector. When your input vector is very large, you will see huge performance gains.

(Also to answer the question in the title: no )

+11
source

All Articles