在Clojure中查找与谓词匹配的元素的索引? [英] Find index of an element matching a predicate in Clojure?
问题描述
使用Clojure,如何在此向量中找到具有正值的第一个索引 [ - 1 0 3 7 9]
?
With Clojure, how do I find the first index with a positive value in this vector [-1 0 3 7 9]
?
我知道你可以使用第一个
和过滤器
获得更优雅的第一个结果:
I know you can get the first result of something rather elegantly with first
and filter
:
(first(filter pos?[-1 0 99 100 101]))
此代码返回值 99
。我想要的答案是 2
的索引。
This code returns the value 99
. The answer I want is the index which is 2
.
推荐答案
keep-indexed
,您可以得到满足谓词的索引序列:
Using keep-indexed
you can get a sequence of indices for which a predicate is satisfied:
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
有了这个简单的函数,你可以用下面的表达式解决你的问题:
With this simple function you'll solve your problem with the expression
user=> (first (indices pos? [-1 0 99 100 101]))
2
注意,由于 keep-indexed
(和 indices
)的惰性,整个序列不需要实现不执行无关的计算。
Note that, due to the lazyness of keep-indexed
(and indices
), the entire sequence need not be realized so no extraneous calculations are performed.
这篇关于在Clojure中查找与谓词匹配的元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!