Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: Equivalent to Common Lisp READ function?

Tags:

file

clojure

lisp

When I want to read in an S-expression stored in a file into a running Common Lisp program, I do the following:

(defun load-file (filename)
  "Loads data corresponding to a s-expression in file with name FILENAME."
  (with-open-file (stream filename)
    (read stream)))

If, for example, I have a file named foo.txt that contains the S-expression (1 2 3), the above function will return that S-expression if called as follows: (load-file "foo.txt").

I've been searching and searching and have not found an equally elegant solution in Clojure. Any ideas?

Thanks!

like image 827
jkndrkn Avatar asked May 18 '10 00:05

jkndrkn


1 Answers

You can do e.g.

(require '[clojure.contrib.io :as io])

(io/with-in-reader (io/file "foo.txt") (read))
; => (1 2 3)

Note that you'll likely want to rebind *read-eval* to false first. Also note that the above works with current contrib HEAD (and will almost certainly work in 1.2 when it's released); for Clojure 1.1, the same functionality is available in the clojure.contrib.duck-streams and clojure.contrib.java-utils namespaces.

like image 197
Michał Marczyk Avatar answered Sep 25 '22 01:09

Michał Marczyk