Skip to content

Instantly share code, notes, and snippets.

@lewang
Last active August 2, 2017 19:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lewang/ac6c398e95c100d99d9626023dd16ec6 to your computer and use it in GitHub Desktop.
Save lewang/ac6c398e95c100d99d9626023dd16ec6 to your computer and use it in GitHub Desktop.
;;; `filter' **MAY** introduce chunkedness, therefore should only be used with
;;; pure functions.
(defn integers-from [n]
(lazy-seq (cons n (do (print \.) (integers-from (inc n))))))
;;; ⇒ #'user/integers-from
(defn chunked-test [xs]
(let [times-called (atom 0)
predicate? (fn [n]
(swap! times-called inc)
true)]
(->> xs
(filter predicate?)
first)
(println (format "called %s times on xs" @times-called))
(if (= 1 @times-called)
:not-chunked
:chunked)))
(chunked-test (integers-from 1))
;;; ⇒ :not-chunked
;;; ⇒ <out>
;;; .called 1 times on xs
(chunked-test (range 33))
;;; ⇒ :chunked
;;; ⇒ <out>
;;; called 32 times on xs
(chunked-test (range))
;;; ⇒ :not-chunked
;;; ⇒ <out>
;;; called 1 times on xs
(chunked-test (into [] (range 33)))
;;; ⇒ :chunked
;;; ⇒ <out>
;;; called 32 times on xs
(defn chunked-test-transducer [xs]
(let [times-called (atom 0)
predicate? (fn [n]
(swap! times-called inc)
true)
xform (comp
(filter #(predicate? %))
(take 1))]
(->> xs
(sequence xform)
first)
(println (format "called %s times on xs" @times-called))
(if (= 1 @times-called)
:not-chunked
:chunked)))
(chunked-test-transducer (integers-from 1))
;;; ⇒ :not-chunked
;;; ⇒ <out>
;;; .called 1 times on xs
(chunked-test-transducer (range 33))
;;; ⇒ :not-chunked
;;; ⇒ <out>
;;; called 1 times on xs
(chunked-test-transducer (range))
;;; ⇒ :not-chunked
;;; ⇒ <out>
;;; called 1 times on xs
(chunked-test-transducer (into [] (range 33)))
;;; ⇒ :not-chunked
;;; ⇒ <out>
;;; called 1 times on xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment