Clojure中数组的最后一个元素

Bfc*_*fcm 1 arrays clojure

除了这个函数之外,有没有更简单的方法在clojure中找到数组的最后一个元素?

(fn [l] (if (empty? (rest l)) (first l) (recur (rest l))))
Run Code Online (Sandbox Code Playgroud)

A. *_*ebb 11

对于向量,使用peek持续时间

 user=> (peek [1 2 3 4 5])
 5
Run Code Online (Sandbox Code Playgroud)

对于Java数组,

user=> (let [a (to-array [1 2 3 4 5])] (aget a (dec (alength a))))
5
Run Code Online (Sandbox Code Playgroud)

对于一般集合,您可以使用线性时间获取最后一项last.它的定义与您所做的类似.

user=> (source last)
(def
 ^{:arglists '([coll])
   :doc "Return the last item in coll, in linear time"
   :added "1.0"
   :static true}
 last (fn ^:static last [s]
        (if (next s)
          (recur (next s))
          (first s))))
Run Code Online (Sandbox Code Playgroud)