24 clojure
使用Clojure,如何在此向量中找到具有正值的第一个索引[-1 0 3 7 9]?
我知道你能得到的东西的第一个结果而典雅,first与filter:
(first (filter pos? [-1 0 99 100 101]))
Run Code Online (Sandbox Code Playgroud)
此代码返回值99.我想要的答案是索引2.
Jon*_*nas 40
使用keep-indexed您可以获得满足谓词的索引序列:
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
Run Code Online (Sandbox Code Playgroud)
通过这个简单的功能,您将使用表达式解决您的问题
user=> (first (indices pos? [-1 0 99 100 101]))
2
Run Code Online (Sandbox Code Playgroud)
注意,由于keep-indexed(和indices)的惰性,不需要实现整个序列,因此不执行无关的计算.