2

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.

Community
  • 1
  • 1
Pold
  • 337
  • 1
  • 11

1 Answers1

3

The semantics of clojure.core/read are a bit different than clojure.tools.reader.edn/read.

The arity-3 version takes arguments

  1. stream the input stream
  2. eof-error? a boolean specifying whether you want read to throw an exception at EOF
  3. eof-value a sentinel value to return when EOF is reached

So, I think you want to replace (read r :eof :end) with (read r false :end) as keywords are truthy.

A. Webb
  • 26,227
  • 1
  • 63
  • 95