I'd like to read in a (longer) file in Closure that contains proper LISP syntax. So I think the best way to do so would be to avoid strings. I tried to use the following function:
(defn my-reader
[filename]
(with-open [r (java.io.PushbackReader. (reader filename))]
(binding [*read-eval* false]
(loop [expr (read r :eof :end)]
(if (= :end expr)
(print "The End")
(do
(println expr)
(recur (read r :eof :end))))))))
However, this throws a EOF while reading error.
As a workaround, I've built:
(defn my-reader
[filename]
(with-open [r (java.io.PushbackReader. (reader filename))]
(binding [*read-eval* false]
(loop [expr (read r :eof :end)]
(if (= -1 expr)
(print "The End")
(recur (try
(print (read r :eof :end))
(catch Exception e -1))))))))
But that's pretty ugly. My attempt with the help of How to use clojure.edn/read to get a sequence of objects in a file? was:
(defn my-reader
[filename]
(with-open [r (java.io.PushbackReader. (reader filename))]
(binding [*read-eval* false]
(let [expr (repeatedly (partial read r :eof :theend))]
(dorun (map println (take-while (partial not= :theend) expr)))))))
And didn't work neither (EOF while reading). However, the solution in the other thread works fine (and edn
seem to be the preferred way to read in files). Nevertheless, I'd like to know why my attempts do not work.