Skip to content

Instantly share code, notes, and snippets.

@hiredman
Created November 11, 2014 21:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiredman/4d8bf007ba7897f11594 to your computer and use it in GitHub Desktop.
Save hiredman/4d8bf007ba7897f11594 to your computer and use it in GitHub Desktop.
(defn unfold [continue? producer seed]
(reify
clojure.core.protocols/CollReduce
(coll-reduce [_ f]
(loop [init seed
seed seed]
(if (reduced? init)
@init
(if (continue? seed)
(let [next (producer seed)]
(recur (f init next) next))
init))))
(coll-reduce [_ f init]
(loop [init (f init seed)
seed seed]
(if (reduced? init)
@init
(if (continue? seed)
(let [next (producer seed)]
(recur (f init next) next))
init))))))
#'user/unfold
user=> (reduce + (unfold pos? dec 10))
55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment