Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the return value of this function?

Tags:

clojure

I write this function, but what's its return value.

(defn read-data [file]
  (let [code (subs (.getName file) 0 3)]
    (with-open [rdr (clojure.java.io/reader file)]
      (drop 1 (line-seq rdr)))))

(def d (read-data "data.db"))

It's OK til now. But when I want print this out.

(clojure.pprint/pprint d)

I got a exception:

Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Stream closed

so I confused, what's wrong? The return value isn't a list? How to debug in this situation as an newbie?

Thanks!

like image 635
Kane Avatar asked Feb 20 '23 22:02

Kane


1 Answers

The problem is that line-seq is lazy and that the reader is closed by the time it is evaluated.

That means all the lines need to be read within the scope of your with-open. One option is to force the full evaluation of line-seq by using doall, as shown below.

(drop 1 (doall (line-seq rdr)))

A potential problem with this approach is that you'll get an OutOfMemoryError if the file is larger than the available memory. So, depending on what you are trying to accomplish, there might be other less memory-intensive solutions.

like image 154
Jeremy Avatar answered Mar 03 '23 02:03

Jeremy