Created
August 31, 2011 17:22
-
-
Save rik0/1184113 to your computer and use it in GitHub Desktop.
Unfold in Clojure
This file contains 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
(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)) |
This file contains 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
;; 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