Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created October 8, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjsmith/7af9f91a2e490bd55ebc to your computer and use it in GitHub Desktop.
Save nwjsmith/7af9f91a2e490bd55ebc to your computer and use it in GitHub Desktop.
(ns dropwarlock.reducers)
(defprotocol Reducee
(reduce-with-instructions [this inst f]))
(extend-protocol Reducee
clojure.lang.PersistentVector
(reduce-with-instructions [this [action acc] f]
(case action
:cont (if (empty? this)
[:done acc]
(recur (rest this) (f (first this) acc) f))
:halt [:halted acc])))
(defn map-reducee
[f coll]
(let [[_ acc] (reduce-with-instructions coll
[:cont []]
(fn [x a] [:cont (conj a (f x))]))]
acc))
(defn take-reducee
[n coll]
(let [[_ [acc _]] (reduce-with-instructions coll
[:cont [[] n]]
(fn [x [a cnt]]
[(if (= 1 cnt) :halt :cont) [(conj a x) (dec cnt)]]))]
acc))
(take-reducee 2 [1 2 3])
(map-reducee inc [1 2 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment