Can't you write that function yourself?

(defn realized-length [xs]
  (loop [n 0 xs xs]
    (if (realized? xs)
      (recur (inc n) (rest xs))
      n)))

drop returns a new lazy sequence, with no realized elements, so
naturally you can't ask if the sequence "under" it is realized. If you
want to work at such a low level you can't build a new lazy sequence;
the above avoids that problem by working with the sequence primitives.

user=> (def naturals (rest (iterate inc 0)))
#'user/naturals
user=> (realized-length naturals)
0
user=> (take 10 naturals)
(1 2 3 4 5 6 7 8 9 10)
user=> (realized-length naturals)
10

Note that this does not work for the "base" case of an iterated
sequence, because that is not a lazy-seq but a cons. Seems a bit weird
to me, but then realized? itself is a bit weird...

On Oct 7, 1:46 pm, George Kangas <gwkan...@gmail.com> wrote:
>    Here's a REPL session, wherein I try to use "realized?" on a
>    lazy-seq.
>
> Clojure 1.3.0
>
>     Define the lazy-seq:
>
> user=> (def naturals (iterate inc 0))
> #'user/naturals
>
>     Force realization of the first 1 + 123456 elements:
>
> user=> (time (nth naturals 123456))
> "Elapsed time: 481.349 msecs"
> 123456
>
>     Due to previous realization, the same expression now eval's
> quickly:
>
> user=> (time (nth naturals 123456))
> "Elapsed time: 15.571 msecs"
> 123456
>
>    Now I try to use "realized?" on 123456th element:
>
> user=> (realized? (nth naturals 123456))
> ClassCastException java.lang.Long cannot be cast to
> clojure.lang.IPending  clojure.core/realized? (core.clj:6505)
>
>     Ouch! I guess "realized?" isn't a macro.  Next try:
>
> user=> (realized? (drop 123456 naturals))
> false
>
>    Hmmm... could I be off by one? Let's leave lots of room for error:
>
> user=> (realized? (drop 12345 naturals))
> false
> user=> (realized? (drop 0 naturals))
> false
>
>     Huh? How do I get "realized?" to tell me what I want to know?
>
>     What I want to know, is wether the element at the nth index
>     has been computed and cached.  Maybe something like "realized-
>     length", just for lazy-seq's, which would report how far along
>     the sequence has realization occurred.
>
>     Thanks,
>     George Kangas

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to