[英]Last element of an Array in Clojure
除了此功能外,还有什么简单的方法可以在Clojure中找到数组的最后一个元素?
(fn [l] (if (empty? (rest l)) (first l) (recur (rest l))))
对于矢量,请使用peek恒定时间
user=> (peek [1 2 3 4 5])
5
对于Java数组,
user=> (let [a (to-array [1 2 3 4 5])] (aget a (dec (alength a))))
5
对于常规集合,您可以使用last获得线性时间中的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))))
最简单的方法是使用在线性时间内工作的(last l)
( http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/last )
另一种可能性是反转您的集合并采用第一个元素: ((comp first reverse) l)
。 但这相当慢,因为反向返回非延迟序列。 注意: comp
返回其参数(函数)的组合( http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/comp )
您还可以先将集合转换为向量,然后应用peek: ((comp peek vec) l)
。 这应该具有更好的性能。
另一个:确定集合的长度,并获取最后一个元素(#(nth % (dec (count %))) l)
。
这些函数适用于所有集合类型(例如向量,列表等)。 Clojure中本身没有数组(除非您想使用Java数组)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.