Skip to content

Instantly share code, notes, and snippets.

@divs1210 divs1210/extrapolate.clj
Last active Aug 3, 2018

Embed
What would you like to do?
extrapolate: like iterate, but different
(defn extrapolate
"Returns a lazy seq produced by extrapolating `coll` with given rules.
On each iteration,
`gen-next` is called with the entire seq generated till this iteration
`shrink` is called with the extrapolated seq (`identity` by default)"
([gen-next coll]
(extrapolate gen-next identity coll))
([gen-next shrink coll]
(concat coll
(let [curr (volatile! (seq coll))]
(repeatedly (fn []
(let [next-val (gen-next @curr)]
(vswap! curr #(shrink (concat % [next-val])))
next-val)))))))
;; USAGE
;; =====
;; without shrink (retains head)
;; ==============
(defn fibs-bad []
(extrapolate #(apply + (take-last 2 %))
[0 1]))
(fibs-bad)
;; => (0 1 1 2 3 5 8 ..)
;; with shrink
;; ===========
(defn fibs []
(extrapolate #(apply + %)
rest
[0 1]))
(fibs)
;; => (0 1 1 2 3 5 8 ..)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.