Edited to recognize mapv
and filterv
.
The standard reverse
is defined in terms of reduce
:
(defn reverse [coll]
(reduce conj () coll))
map
and filter
are lazy, so can operate on infinite sequences. There is no way to do this with reduce
.
That being said, reduce
can implement mapv
and filterv
, the eager analogues of map
and filter
.
(defn mapv [f coll]
(vec (reverse (reduce (fn [acc x] (cons (f x) acc)) () coll))))
(defn filterv [pred coll]
(vec (reverse (reduce (fn [acc x] (if (pred x) (cons x acc) acc)) () coll))))
We can do without the reverse
s and the vec
s if we accumulate in vectors:
(defn mapv [f coll]
(reduce (fn [acc x] (conj acc (f x))) [] coll))
(defn filterv [pred coll]
(reduce (fn [acc x] (if (pred x) (conj acc x) acc)) [] coll))
This last is almost how the standard filterv
is implemented.