Здесь (2.6 Where’s My for Loop?) есть такой пример:
(defn indexed [coll] (map vector (iterate inc 0) coll))
(defn index-filter [pred coll]
(when pred
(for [[idx elt] (indexed coll) :when (pred elt)] idx)))
(defn index-of-any [pred coll]
(first (index-filter pred coll)))
, определяюший функцию index-of-any являющуюся аналогом следующей функции на Java:
public static int indexOfAny(String str, char[] searchChars) {
if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
return i;
}
}
}
return -1;
}
В отличии от функции на Java ее аналог на Clojure в начале работы строит отображение индекс->значение. Это на самом деле нужно? Разве нельзя написать вот так?:
(defn index-of-any-helper [pred coll idx]
(when (and pred coll)
(if (pred (first coll))
idx
(recur (butfirst coll) (add idx 1)))))
(defn index-of-any [pred coll]
(index-of-any-helper pred coll 0))