我知道如何使用函数 Last 获取最后一个元素,但是是否有可能获取序列的倒数第二个元素?
(defn last
[args]
(last args))
(last [1 2 3 4]) ;;--> 4 but i want it to return 3
Run Code Online (Sandbox Code Playgroud)
使用reverse、take-last、butlast或nth(这似乎是最快的):
(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
Run Code Online (Sandbox Code Playgroud)