Skip to content

Instantly share code, notes, and snippets.

@halgari

halgari/transducer

Created Mar 25, 2020
Embed
What would you like to do?
(ns scratch)
(defn map [f]
(fn [xf]
(fn
([] (xf))
([acc] (xf acc))
([acc itm]
(xf acc (f itm))))))
(defn filter [f]
(fn [xf]
(fn
([] (xf))
([acc] (xf acc))
([acc itm]
(if (f itm)
(xf acc itm)
acc)))))
(defn compose [a b]
(fn [x]
(a (b x))))
(defn transduce [xform rf coll]
(let [rf (xform rf)
start (rf)]
(reduce rf start coll)0))
(defprotocol ITransducer
(start [this])
(on-next! [this itm])
(on-end! [this])
(set-next! [this nxt]))
(defrecord Map [f next]
ITransducer
(start [this]
(start @next))
(on-next! [this itm]
(on-next! @next (f itm)))
(on-end! [this]
(on-end! @next))
(set-next! [this nxt]
(vreset! next nxt)))
(defrecord Filter [f next]
ITransducer
(start [this]
(start @next))
(on-next! [this itm]
(if (f itm)
(on-next! @next itm)))
(on-end! [this]
(on-end! @next))
(set-next! [this nxt]
(vreset! next nxt)))
(defn compose [a b]
(set-next! a b))
(defn transduce [xform rf coll]
(let [acc (volatile! (rf))]
(set-next! xform (reify ITransducer
(start [this]
(vreset! acc (rf)))
(on-next! [this itm]
(vswap! acc rf itm))
(on-end! [this]
nil)))
(doseq [itm coll]
(on-next! xform itm))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment