diff options
author | scgilardi <scgilardi@gmail.com> | 2008-06-28 20:03:16 +0000 |
---|---|---|
committer | scgilardi <scgilardi@gmail.com> | 2008-06-28 20:03:16 +0000 |
commit | cef84addca7796ec9387d2e87c40447e9fc541bd (patch) | |
tree | 5a0513ff879b2704217e97c3e2848192efcf93f3 | |
parent | 8aca82ac404998a7584d99e1039e60e8ac5b3a20 (diff) |
add pred.clj, various predicates for convenience, readability
-rw-r--r-- | def.clj | 7 | ||||
-rw-r--r-- | lazy-seqs.clj | 23 |
2 files changed, 29 insertions, 1 deletions
@@ -17,6 +17,13 @@ (clojure/in-ns 'def) (clojure/refer 'clojure) +(defmacro init-once + "Initializes a var exactly once. The var must already exist." + [var init] + `(let [v# (resolve '~var)] + (when-not (.isBound v#) + (.bindRoot v# ~init)))) + (defmacro defvar "Defines a var with an optional intializer and doc string" ([name] diff --git a/lazy-seqs.clj b/lazy-seqs.clj index 6b4b4c7b..9a8aa714 100644 --- a/lazy-seqs.clj +++ b/lazy-seqs.clj @@ -17,6 +17,8 @@ ;; ;; fibs - based on code from Rich Hickey at the Clojure wiki [3] ;; +;; powers-of-2 - all the powers of 2 +;; ;; [1] http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf ;; [2] http://clj-me.blogspot.com/2008/06/primes.html ;; [3] http://en.wikibooks.org/wiki/Clojure_Programming#Examples @@ -29,6 +31,16 @@ (lib/use def) +(defn isqrt + "Returns the integer square root of n" + [n] + (loop [xn 1] + (prn xn) + (let [xn1 (quot (+ xn (quot n xn)) 2)] + (if (= xn1 xn) + xn1 + (recur xn1))))) + (defvar primes (lazy-cat [2 3 5 7] (let [primes-from @@ -43,10 +55,19 @@ "A lazy sequence of all the prime numbers.") (defvar fibs - (concat [0 1] + (lazy-cat [0 1] (let [rest-fn (fn rest-fn [a b] (let [next (+ a b)] (lazy-cons next (rest-fn b next))))] (rest-fn 0 1))) "A lazy sequence of all the fibonacci numbers.") + +(defvar powers-of-2 + (lazy-cons 1 + (let [rest-fn + (fn rest-fn [n] + (let [next (bit-shift-left n 1)] + (lazy-cons next (rest-fn next))))] + (rest-fn 1))) + "A lazy sequence of all the powers of 2") |