Skip to content

Instantly share code, notes, and snippets.

@divs1210
Last active August 3, 2018 06:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divs1210/09a40bb2830fbcee11d3806888ef0f62 to your computer and use it in GitHub Desktop.
Save divs1210/09a40bb2830fbcee11d3806888ef0f62 to your computer and use it in GitHub Desktop.
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