Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@halgari
Created March 25, 2020 14:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save halgari/97c3b3e94e68f0d407f77cae6ac1de65 to your computer and use it in GitHub Desktop.
Save halgari/97c3b3e94e68f0d407f77cae6ac1de65 to your computer and use it in GitHub Desktop.
(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