Clojure中最高键的返回值 [英] Return value of highest key in Clojure
问题描述
我正在使用这两组键值对,它们由另一个函数返回。我想写一个函数,总是找到最高的键,并返回其对应的值。在这个例子中,我会返回2,因为499是最高的键。我使用的数据是
I'm working with these two groups of key value pairs, which is being returned by another function. I'd like to write a function that will always find the highest key and return its corresponding value. In this example, I'd be returning 2 because 499 is the highest key. The data that I am working with is
({-99 0, 99 0} {-99 2, 499 2})
当我调用
(type ({-99 0, 99 0} {-99 2, 499 2}))
b $ b
在负责返回数据的函数中,我回到了
Within the function that is responsible for returning that data it, I get back
(clojure.lang.PersistentTreeMap clojure.lang.PersistentTreeMap)
我希望有所帮助。谢谢!
I hope that helps. Thanks!
推荐答案
此函数将返回一个Clojure排序映射的最右边的条目$ c> clojure.lang.PersistentTreeMap )在对数时间:
This function will return the rightmost entry of a Clojure sorted map (the built-in implementation is called clojure.lang.PersistentTreeMap
) in logarithmic time:
(defn rightmost
"Takes a Clojure sorted map sm and returns the entry at the greatest
key (as determined by sm's comparator)."
[sm]
(first (rseq sm)))
示例:
(rightmost (sorted-map 1 1 2 2 3 3))
;= [3 3]
然后,您可以使用 val
函数取出值。
You can then fish out the value using the val
function.
所有 max-key
/ apply max
- 以线性时间工作改为。不用说,这是一个巨大的区别。
All the max-key
/ apply max
-based solutions work in linear time instead. Needless to say, it's a huge difference.
如果另一个函数可以说服返回 data.avl maps,您可以使用 nth
在对数时间的任何索引处访问元素:
If the other function could be convinced to return data.avl maps instead, you could access the element at any index in logarithmic time using nth
:
;; works for data.avl sorted maps, not the built-ins
(nth (avl/sorted-map 1 1 2 2 3 3) 2)
;= [3 3]
这篇关于Clojure中最高键的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!