Last active
August 3, 2018 06:04
-
-
Save divs1210/09a40bb2830fbcee11d3806888ef0f62 to your computer and use it in GitHub Desktop.
extrapolate: like iterate, but different
This file contains 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
(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