Skip to content

Instantly share code, notes, and snippets.

@richhickey
Last active June 10, 2023 14:30
Show Gist options
  • Save richhickey/b5aefa622180681e1c81 to your computer and use it in GitHub Desktop.
Save richhickey/b5aefa622180681e1c81 to your computer and use it in GitHub Desktop.
(require '[clojure.core.async :as a])
(def xform (comp (map inc)
(filter even?)
(dedupe)
(flatmap range)
(partition-all 3)
(partition-by #(< (apply + %) 7))
(flatmap flatten)
(random-sample 1.0)
(take-nth 1)
(keep #(when (odd? %) (* % %)))
(keep-indexed #(when (even? %1) (* %1 %2)))
(replace {2 "two" 6 "six" 18 "eighteen"})
(take 11)
(take-while #(not= 300 %))
(drop 1)
(drop-while string?)
(remove string?)))
(def data (vec (interleave (range 18) (range 20))))
;; lazily transform the data
(sequence xform data)
;; reduce with a transformation (no laziness)
(transduce xform + 0 data)
;;build one collection from a transformation of another, again no laziness
(into [] xform data)
;;create a recipe for a transformation, which can be subsequently sequenced, iterated or reduced
(iteration xform data)
;;transform everything that goes through a channel - same transducer stack!
(let [c (a/chan 1 xform)]
(a/thread (a/onto-chan c data))
(a/<!! (a/into [] c)))
@tiye
Copy link

tiye commented Oct 28, 2017

Tried with shadow-cljs clj-repl. flatmap undefined so I used mapcat, iteration undefined so I used iterate. But why?

@peter-lyons-kehl
Copy link

flatmap was replaced with mapcat: https://dev.clojure.org/jira/browse/CLJ-1494

@benjamin-asdf
Copy link

From the explanation comment I am assuming iteration was what is now called eduction. Btw iteration is defined since 1.11 but it is something quite different. Not a transducable context but a function that returns a seqable/reducable (read its docstring).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment