Skip to content

Instantly share code, notes, and snippets.

@amalloy
Created January 25, 2011 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amalloy/b549634b4d855cde88c2 to your computer and use it in GitHub Desktop.
Save amalloy/b549634b4d855cde88c2 to your computer and use it in GitHub Desktop.
(defn unfold
"Next and done? are functions that operate on a seed. next should return a pair, [value new-seed]; the value half of the pair is inserted into the resulting list, while the new-seed is used to continue unfolding. Notably, the value is never passed as an argument to either next or done?."
[next done? seed]
(map first
(rest
(take-while (comp (complement done?) second)
(iterate (comp next second)
[nil seed])))))
(defn fibs []
(unfold (fn [[a b]] [a [b (+ a b)]]) (constantly false) [0 1]))
user> (take 10 (fibs))
(0 1 1 2 3 5 8 13 21 34)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment