3

我有以下功能:

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

是否可以避免使用 clojure.core.reducers 创建中间 2 元素集合?

4

1 回答 1

1

不是开箱即用。但是你可以:

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

看:

(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))))
于 2013-02-13T16:56:41.163 回答