Skip to content

Commit

Permalink
Proper (reduced) handling in transducers
Browse files Browse the repository at this point in the history
  • Loading branch information
tonsky committed Dec 1, 2014
1 parent 1f78245 commit 28826e4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src-clj/acha/server.clj
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,12 @@
(defn- entity->flat [rf]
(completing
(fn [result entity]
(reduce-kv (fn [result attr val]
(if (= attr :db/id)
result
(rf result [(:db/id entity) attr val])))
result entity))))
(util/-reduce-kv
(fn [result attr val]
(if (= attr :db/id)
result
(rf result [(:db/id entity) attr val])))
result entity))))

(defn full-dump []
(let [ent->datoms (comp entity->flat
Expand Down
20 changes: 20 additions & 0 deletions src-clj/acha/util.clj
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,23 @@
(defn max-by [f [x & xs]]
(reduce #(if (pos? (compare (f %1) (f %2))) %1 %2) x xs))

(defn -reduce
"Variant of reduce that does not unwrap (reduced)"
[f init coll]
(reduce #(let [result (f %1 %2)]
(cond-> result
;; wrap twice because reduce will unwrap one reduced
;; but we want to pass that info down the line
(reduced? result) reduced))
init coll))

(defn -reduce-kv
"Variant of reduce-kv that does not unwrap (reduced)"
[f init coll]
(reduce-kv #(let [result (f %1 %2 %3)]
(cond-> result
;; wrap twice because reduce-kv will unwrap one reduced
;; but we want to pass that info down the line
(reduced? result) reduced))
init coll))

0 comments on commit 28826e4

Please sign in to comment.