Skip to content

Instantly share code, notes, and snippets.

@rik0
Created August 31, 2011 17:22
Show Gist options
  • Save rik0/1184113 to your computer and use it in GitHub Desktop.
Save rik0/1184113 to your computer and use it in GitHub Desktop.
Unfold in Clojure
(ns unfold-examples
(:use [unfold-util]))
(defn unfold-tails [s]
(unfold empty? identity rest s))
(defn unfold-map [f s]
(unfold empty? #(f (first %)) rest s))
;; Enrico Franchi (c) 2011
;; Released under the terms of the MIT License
;; http://www.opensource.org/licenses/mit-license.php
(ns unfold-util
(:use [clojure.test]))
(defn unfold
([p f g seed tail-g]
(lazy-seq
(if (p seed)
(tail-g seed)
(cons (f seed)
(unfold p f g (g seed))))))
([p f g seed]
(unfold p f g seed (fn [_] ()))))
(deftest standard-unfold []
(is (= (set (unfold #(= 0 %) identity dec 10))
(set (range 1 11)))))
(deftest infinite-unfold []
(is (=
(take 10 (unfold
(fn [x] false)
identity
inc
0))
(take 10 (iterate inc 0)))))
(run-tests)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment