tags:

views:

78

answers:

1

Hi;

What would be an ideomatic way in Clojure to get a lazy sequence over a file containing float values serialized from Java? (I've toyed with a with-open approach based on line-reading examples but cannot seem to connect the dots to process the stream as floats.)

Thanks.

+10  A: 
(defn float-seqs [#^java.io.DataInputStream dis]
  (lazy-seq
    (try
      (cons (.readFloat dis) (float-seqs dis))
      (catch java.io.EOFException e
        (.close dis)))))

(with-open [dis (-> file java.io.FileInputStream. java.io.DataInputStream.)]
  (let [s (float-seqs dis)]
    (doseq [f s]
      (println f))))

You are not required to use with-open if you are sure you are going to consume the whole seq.

If you use with-open, double-check that you're not leaking the seq (or a derived seq) outside of its scope.

cgrand
Elegant. Thank you.
Cumbayah
Great : it illuminated the use of lazy-seq in my mind. It finally clicked.
Peter Tillemans