Return the last item in coll, in linear time
user=> (last [1 2 3 4 5]) 5 user=> (last ["a" "b" "c" "d" "e"]) "e" user=> (last {:one 1 :two 2 :three 3}) [:three 3] user=> (last []) nil ;; but be careful with what you expect from a map (or set): user=> (last {:a 1 :b 2 :c 3 :d 4 :e 5 :f 6 :g 7 :h 8 :i 9}) [:a 1]
;really slow reverse ;put the last item of the list at the start of a new list, and recur over all but the last item of the list. ;butlast acts similar to next in that it returns null for a 1-item list. (defn my-reverse ([a-list] (cond (= a-list nil) nil :else (cons (last a-list) (my-reverse (butlast a-list))))))
;; Prefer clojure.core/peek over `last` for potentially large vectors. user=> (def v (into [] (take 900900 (range)))) #'user/v user=> (time (last v)) "Elapsed time: 24.460958 msecs" 900899 user=> (def v2 (into [] (take 900900 (range)))) #'user/v2 user=> (time (peek v2)) "Elapsed time: 0.020498 msecs" 900899 ;; For a deep dive into why Rich Hickey chose not to make `last` performant ;; for large vectors, please see: ;; https://gist.github.com/reborg/dc8b0c96c397a56668905e2767fd697f
;; last is also inefficient for sorted-sets and sorted-maps, and ;; peek doesn't work for these, so we can combine `first` with `rseq` ;; to efficiently get the last element on large sorted- collections instead (def sm (into (sorted-map) (map vector (range 1e6) (repeatedly #(rand-int 100))))) (time (last sm)) "Elapsed time: 144.298867 msecs" ;; => [999999 42] (time (first (rseq sm))) "Elapsed time: 0.024408 msecs" ;; => [999999 42]
;; Beside using clojure.core/peek for fast access to the last element in ;; a large vector, you can also use (first (rseq)) which is performant as well (def v (into [] (take 900900 (range)))) (time (last v)) "Elapsed time: 24.825208 msecs" 900899 (def v2 (into [] (take 900900 (range)))) (time (peek v2)) "Elapsed time: 0.02343 msecs" 900899 (def v3 (into [] (take 900900 (range)))) (time (first (rseq v3))) "Elapsed time: 0.02581 msecs" 900899
Returns the first item in the collection. Calls seq on its argument. If coll is nil, returns nil...
Returns a seq of the items after the first. Calls seq on its argument. If there are no more items...
Returns a possibly empty seq of the items after the first. Calls seq on its argument.
Returns a seq of the last n items in coll. Depending on the type of coll may be no better than li...
For a list or queue, same as first, for a vector, same as, but much more efficient than, last. If ...
last