使用 Clojure,如何找到该向量中第一个具有正值的索引[-1 0 3 7 9]
?
我知道你可以相当优雅地得到第一个结果first
and filter
:
(first (filter pos? [-1 0 99 100 101]))
这段代码返回值99
。我想要的答案是索引2
.
Using keep-indexed http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/keep-indexed您可以获得满足谓词的索引序列:
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
通过这个简单的函数,您可以用表达式解决您的问题
user=> (first (indices pos? [-1 0 99 100 101]))
2
请注意,由于懒惰keep-indexed
(and indices
),不需要实现整个序列,因此不需要执行额外的计算。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)