diff options
author | Christophe Grand <christophe@cgrand.net> | 2009-01-06 00:30:56 +0000 |
---|---|---|
committer | Christophe Grand <christophe@cgrand.net> | 2009-01-06 00:30:56 +0000 |
commit | 422ec0ad734d951d41b6950b65cb42818013430e (patch) | |
tree | a444b6d724d8d6364294041684ad461b70c5d6d0 /src | |
parent | 4b7ca1275029a6de7aa4f57e693da6e74f54e162 (diff) |
added rec-cat, rec-cons and reductions
Diffstat (limited to 'src')
-rw-r--r-- | src/clojure/contrib/seq_utils.clj | 38 |
1 files changed, 37 insertions, 1 deletions
diff --git a/src/clojure/contrib/seq_utils.clj b/src/clojure/contrib/seq_utils.clj index 58b5914b..12ca1fca 100644 --- a/src/clojure/contrib/seq_utils.clj +++ b/src/clojure/contrib/seq_utils.clj @@ -1,7 +1,7 @@ ;;; seq_utils.clj -- Sequence utilities for Clojure ;; by Stuart Sierra, http://stuartsierra.com/ -;; last updated December 16, 2008 +;; last updated January 05, 2009 ;; Copyright (c) Stuart Sierra, 2008. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse @@ -79,3 +79,39 @@ (reduce (fn [counts x] (assoc counts x (inc (get counts x 0)))) {} coll)) + +;; recursive sequence helpers by Christophe Grand +;; see http://clj-me.blogspot.com/2009/01/recursive-seqs.html +(defmacro rec-cat + "Similar to lazy-cat but binds the resulting sequence using the supplied + binding-form, allowing recursive expressions. The first collection + expression must not be recursive and must yield a non-nil seq." + [binding-form expr & rec-exprs] + `(let [rec-rest# (atom nil) + result# (lazy-cat ~expr (force @rec-rest#)) + ~binding-form result#] + (swap! rec-rest# (constantly (delay (lazy-cat ~@rec-exprs)))) + result#)) + +(defmacro rec-cons + "Similar to lazy-cons but binds the resulting sequence using the supplied + binding-form, allowing recursive expressions. The first expression must + not be recursive." + [binding-form expr & rec-exprs] + `(let [rec-rest# (atom nil) + result# (lazy-cons ~expr (force @rec-rest#)) + ~binding-form result#] + (swap! rec-rest# (constantly (delay (lazy-cat ~@rec-exprs)))) + result#)) + +;; reductions by Chris Houser +;; see http://groups.google.com/group/clojure/browse_thread/thread/3edf6e82617e18e0/58d9e319ad92aa5f?#58d9e319ad92aa5f +(defn reductions + "Returns a lazy seq of the intermediate values of the reduction (as + per reduce) of coll by f, starting with init." + ([f coll] + (if (seq coll) + (rec-cons self (first coll) (map f self (rest coll))) + (cons (f) nil))) + ([f init coll] + (rec-cons self init (map f self coll))))
\ No newline at end of file |