exception - How to build a vector via a call to reduce -
i'm trying figure why particular function isn't working expected. suspect error message has way i'm creating empty vector accumulator.
i have simple function returns sequence of 2-element vectors:
(defn zip-with-index "returns sequence in each element of form [i c] index of element , c element @ index." [coll] (map-indexed (fn [i c] [i c]) coll))
that works fine. problem comes when try use in function
(defn indexes-satisfying "returns vector containing indexes of coll satisfy predicate p." [p coll] (defn accum-if-satisfies [acc zipped] (let [idx (first zipped) elem (second zipped)] (if (p elem) (conj acc idx) (acc)))) (reduce accum-if-satisfies (vector) (zip-with-index coll)))
it compiles, when attempt use error:
user=> (indexes-satisfying (partial > 3) [1 3 5 7]) arityexception wrong number of args (0) passed to: persistentvector clojure.lang.afn.throwarity (afn.java:437)
i can't figure out what's going wrong here. if there more 'clojure-like' way of doing i'm trying do, i'm interested in hearing also.
the problem on else clause of accum-if-satisfies
, should acc
not (acc)
.
you use filter
, map
instead of reduce
. that:
(map #(first %) (filter #(p (second %)) (zip-with-index coll)))
you call map-indexed
vector
instead of (fn [i c] [i c])
. whole code that:
(defn indexes-satisfying [p coll] (map #(first %) (filter #(p (second %)) (map-indexed vector coll))))
Comments
Post a Comment