Search code examples
clojuresequence

How can i get the second to last element of a Sequence? Clojure


i know how to get the last element with the function last but is it possible to get the second to last element of a Sequence?

(defn last
  [args]
   (last args))
(last [1 2 3 4]) ;;--> 4 but i want it to return 3

Solution

  • Use reverse, take-last, butlast or nth (this one seems to be the fastest):

    (defn second-to-last1 [s]
      (second (reverse s)))
    
    (second-to-last1 (range 100))
    => 98
    
    (defn second-to-last2 [s]
      (first (take-last 2 s)))
    
    (second-to-last2 (range 100))
    => 98
    
    (defn second-to-last3 [s]
      (last (butlast s)))
    
    (second-to-last3 (range 100))
    => 98
    
    (defn second-to-last4 [s]
      (nth s (- (count s) 2) nil))
    
    (second-to-last4 (range 100))
    => 98