Last active
November 2, 2015 23:21
-
-
Save killme2008/9754a2888970d22b2fa9 to your computer and use it in GitHub Desktop.
unfold in clojure as Stream.unfold in elixir
This file contains hidden or 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 unfold | |
| "Creates a lazy sequence based on start accumulator and step functon. | |
| The step function transform the state as below: | |
| step(value) -> [current-value, next-accumulator] | |
| For example: | |
| (unfold 5 (fn [n] | |
| (when-not (zero? n) | |
| [n (dec n)]))) | |
| " | |
| [start step] | |
| (when start | |
| (lazy-seq | |
| (let [[cs ns] (step start)] | |
| (when cs | |
| (cons cs | |
| (lazy-seq (unfold ns step)))))))) | |
| (take 5 (unfold [0 1] (fn [[n1 n2]] [n1 [n2 (+' n1 n2)]]))) | |
| (unfold 5 (fn [n] | |
| (when-not (zero? n) | |
| [n (dec n)]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment