-
-
Save fr33m0nk/d3bd6ac2ba80f8fb459f63183d080343 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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