From c50e46e9700eac039ff4d9e7764c7262e4d40114 Mon Sep 17 00:00:00 2001 From: Christophe Grand Date: Wed, 16 Sep 2015 13:31:22 +0200 Subject: [PATCH] Add standard arities to into. --- src/net/cgrand/xforms.clj | 60 +++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/src/net/cgrand/xforms.clj b/src/net/cgrand/xforms.clj index c6c91e0..dff3b6b 100644 --- a/src/net/cgrand/xforms.clj +++ b/src/net/cgrand/xforms.clj @@ -73,32 +73,42 @@ ([f init] (reduce (fn ([] init) ([acc] (f acc)) ([acc x] (f acc x)))))) +(defn- into-rf [to] + (cond + (instance? clojure.lang.IEditableCollection to) + (if (map? to) + (kvrf + ([] (transient to)) + ([acc] (persistent! acc)) + ([acc x] (conj! acc x)) + ([acc k v] (assoc! acc k v))) + (fn + ([] (transient to)) + ([acc] (persistent! acc)) + ([acc x] (conj! acc x)))) + (map? to) + (kvrf + ([] to) + ([acc] acc) + ([acc x] (conj acc x)) + ([acc k v] (assoc acc k v))) + :else + (fn + ([] to) + ([acc] acc) + ([acc x] (conj acc x))))) + (defn into - "Returns a transducer which accumulate every input in a collection and outputs only the accumulated collection." - [coll] - (reduce (cond - (instance? clojure.lang.IEditableCollection coll) - (if (map? coll) - (kvrf - ([] (transient coll)) - ([acc] (persistent! acc)) - ([acc x] (conj! acc x)) - ([acc k v] (assoc! acc k v))) - (fn - ([] (transient coll)) - ([acc] (persistent! acc)) - ([acc x] (conj! acc x)))) - (map? coll) - (kvrf - ([] coll) - ([acc] acc) - ([acc x] (conj acc x)) - ([acc k v] (assoc acc k v))) - :else - (fn - ([] coll) - ([acc] acc) - ([acc x] (conj acc x)))))) + "Like clojure.core/into but with a 1-arg arity returning a transducer which accumulate every input in a collection and outputs only the accumulated collection." + ([to] + (reduce (into-rf to))) + ([to from] + (into to identity from)) + ([to xform from] + (let [rf (xform (into-rf to))] + (if-let [rf (and (map? from) (satisfies? clojure.core.protocols/IKVReduce from) (some-kvrf rf))] + (rf (clj/reduce-kv rf (rf) from)) + (rf (clj/reduce rf (rf) from)))))) (defmacro ^:private or-instance? [class x y] (let [xsym (gensym 'x_)]