Last active
August 29, 2015 14:14
-
-
Save matlux/2e02adbcb3326be50caf to your computer and use it in GitHub Desktop.
This file contains hidden or 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 transducers.core) | |
(defn my-filter [pred coll] | |
(reduce #(if (pred %2) (conj %1 %2) %1) [] coll)) | |
(defn my-map [f coll] | |
(reduce (fn [r x] | |
(conj r (f x))) [] coll)) | |
(comment | |
;;xform :: (a -> b -> a) -> (a -> b -> a) | |
;;map :: (a -> b) -> (a -> b -> a) -> (a -> b -> a) | |
;;filter :: (b -> Boolean) -> (a -> b -> a) -> (a -> b -> a) | |
) | |
(defn my-map-trans [f] | |
(fn [rf] | |
(fn [acc el] | |
(rf acc (f el))))) | |
(defn my-filter-trans [pred] | |
(fn [rf] | |
(fn [acc el] | |
(if (pred el) | |
(rf acc el) | |
acc)))) | |
(filter even? (range 5)) | |
(map inc (range 5)) | |
#((map inc) ((filter even?) %1)) | |
(fn [rf] | |
((map inc) ((filter even?) rf))) | |
;; equivalent | |
(into [] (comp (map inc) (filter even?)) (range 5)) ;; traditional composition | |
(into [] #((map inc) ((filter even?) %1)) (range 5)) ;; tranducers | |
(into [] (fn [rf] | |
((map inc) ((filter even?) rf))) (range 5)) | |
(into [] | |
(fn [rf] | |
(->> rf | |
((filter even?)) | |
((map inc)))) | |
(range 5)) | |
;;reversed | |
(into [] (comp (filter even?) (map inc)) (range 5)) | |
;; partition-all | |
(defn partition-all-transducer [n] | |
(fn [rf] | |
(let [!coll (atom [])] | |
(fn | |
([] | |
(rf)) | |
([acc] | |
(let [res (rf acc @!coll)] | |
(rf res))) | |
([acc el] | |
(swap! !coll conj el) | |
(if (= n (count @!coll)) | |
(let [res (rf acc @!coll)] | |
(reset! !coll []) | |
res) | |
acc)))))) | |
(into [] | |
() | |
(range 5)) | |
(def mycode '(defn foo [x] | |
(map inc x))) | |
(reduce) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment