Question

I have a following function:

(defn map-pairs [f coll]
  (map f (partition 2 1 coll)))

Is it possible to avoid creating of the intermediate 2-element collections using clojure.core.reducers?

Was it helpful?

Solution

Not out of the box. But you can:

=> (into [] (map2 + (range 10)))
[1 3 5 7 9 11 13 15 17]

See:

(deftype Fn2 [f1 f ^:volatile-mutable a ^:volatile-mutable b]
  clojure.lang.IFn
  (invoke [this] (f1))
  (invoke [this _] (set! b this)) ; hack to init the sentinel
  (invoke [this ret v] 
    (set! a b)
    (set! b v)
    (if (identical? a this)
      ret
      (f1 ret (f a b))))
  #_(invoke [this ret k v] to do))

(defn fn2 [f1 f] 1
  (let [f2 (Fn2. f1 f nil nil)]
    (f2 nil)
    f2))

(defn map2 [f coll]
  (r/reducer coll
    (fn [f1]
      (fn2 f1 f))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top