On Thu, Feb 12, 2009 at 12:22 PM, Meikel Brandmeyer <m...@kotka.de> wrote: > Hi, > > Am 12.02.2009 um 18:29 schrieb Mark Volkmann: > >> (def f-infinite-seq (map f (iterate inc 0))) ; values 0 through infinity >> >> (println "The first is" (first f-infinite-seq)) >> (println "The third is" (nth f-infinite-seq 2)) > > The result is cached in f-infinite-seq. So as long as you hold > onto the head of the seq, the value will be there, even if you > don't use the result of the "first" call. > > The solution is probably to not hold onto the head. Either > feed the infinite seq directly to the consumer, without storing > it in a global Var or a local.
Like this? (defn consumer [seq] (println (first seq)) (println (nth seq 2))) (consumer (map f (iterate inc 0))) This puts the lazy sequence returned by map into the local variable "seq" for the duration of the call to consumer. The first call to println in consumer evaluates (f 0). The second call to println in consumer evaluates (f 1) and (f 2), but not (f 0) since it was cached. This is fine as long as consumer doesn't evaluate so many items in the infinite lazy sequence that the memory isn't exhausted before consumer returns. Is the approach you describe next, using a factory function that returns new instances of the lazy sequence each time it is called, the only solution for consumers that may evaluate a large number of items and don't want the results to be cached? Or use a factory function which > returns a fresh seq, everytime you call it. > > (defn f-infinite-seq > [] > (map f (iterate inc 0))) > > (println "The first is" (first (f-infinite-seq))) > (println "The third is" (nth (f-infinite-seq) 2))) -- R. Mark Volkmann Object Computing, Inc. --~--~---------~--~----~------------~-------~--~----~ 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 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 -~----------~----~----~----~------~----~------~--~---