Created
October 8, 2015 21:09
-
-
Save nwjsmith/7af9f91a2e490bd55ebc 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 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