ClojureDocs

Nav

Namespaces

drop-last

clojure.core

Available since 1.0 (source)
  • (drop-last coll)
  • (drop-last n coll)
Return a lazy sequence of all but the last n (default 1) items in coll
2 Examples

(drop-last [1 2 3 4])
;=> (1 2 3) 

(drop-last -1 [1 2 3 4])
;=> (1 2 3 4) 

(drop-last 0 [1 2 3 4])
;=> (1 2 3 4) 

(drop-last 5 [1 2 3 4])
;=> ()

;; works differently with any seq.
;; but with some the last items become ambiguous.
(drop-last 2 (vector 1 2 3 4))
;=> (1 2)
(drop-last 2 (list 1 2 3 4 ))
;=> (1 2)
(drop-last 2 {:a 1 :b 2 :c 3 :d 4})
;=> ([:a 1] [:b 2])
;; Using `drop-last` vs. using `butlast`

(def v [1 2 3 4])

(butlast v)              ;;=> (1 2 3)
(drop-last v)            ;;=> (1 2 3)
(drop-last 2 v)          ;;=> (1 2) butlast can't do this
(butlast 2 v)            ;;=> ArityException
(drop-last 0 v)          ;;=> (1 2 3 4) 
(drop-last -1 v)         ;;=> (1 2 3 4)

;; Performance differences:
;;  - `butlast`, linear time
;;  - `drop-last`, lazy, efficient, more flexible, constant time(?) 
;;  - `pop`, constant but requires a vector

(def r (range 10000))

(time (butlast r))       ;;=> "Elapsed time: 6.379 msecs"
(time (drop-last r))     ;;=> "Elapsed time: 0.0475 msecs"
(time (drop-last 2 r))   ;;=> "Elapsed time: 0.0569 msecs"
(time (drop-last 0 r))   ;;=> "Elapsed time: 0.098 msecs"
(time (drop-last -1 r))  ;;=> "Elapsed time: 0.0615 msecs"

(def r-vec (vec r))      ;; to work like `butlast` pop needs a vector 
(time (pop r-vec))       ;;=> "Elapsed time: 0.062 msecs"
See Also

Returns a lazy sequence of all but the first n items in coll. Returns a stateful transducer when n...

Added by gstamp

Returns a lazy sequence of the items in coll starting from the first item for which (pred item) re...

Added by gstamp

Return a seq of all but the last item in coll, in linear time

Added by huahaiy

For a list or queue, returns a new list/queue without the first item, for a vector, returns a new ...

Added by Crowbrammer
1 Note
    By , created 7.0 years ago

    drop-last is lazy and implemented with map, whereas butlast is not lazy and implemented with loop and recur.