Skip to content

Instantly share code, notes, and snippets.

@killme2008
Last active November 2, 2015 23:21
Show Gist options
  • Select an option

  • Save killme2008/9754a2888970d22b2fa9 to your computer and use it in GitHub Desktop.

Select an option

Save killme2008/9754a2888970d22b2fa9 to your computer and use it in GitHub Desktop.
unfold in clojure as Stream.unfold in elixir
(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