Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing and reading lists from a file in Clojure

Tags:

clojure

I have a Clojure data structure of the form:

{:foo '("bar" "blat")}

and have tried writing them to a file using the various pr/prn/print. However, each time the structure is written as

{:foo ("bar" "blat")}

then when I try to read in it using load-file, I get an error such as:

java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IF n (build-state.clj:79)

presumably as the list is being evaluated as a function call when it is read. Is there any way to write the structure out with the lists in their quoted form?

thanks, Nick

like image 748
eldoctoro Avatar asked Feb 28 '23 23:02

eldoctoro


1 Answers

The inverse of printing is usually reading, not loading.

user> (read-string "{:foo (\"bar\" \"blat\")}")
{:foo ("bar" "blat")}

If you really need to print loadable code, you need to quote it twice.

user> (pr-str '{:foo '("bar" "blat")})
"{:foo (quote (\"bar\" \"blat\"))}"

user> (load-string (pr-str '{:foo '("bar" "blat")}))
{:foo ("bar" "blat")}
like image 189
Brian Carper Avatar answered Mar 08 '23 04:03

Brian Carper