Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27286

Clojure form to string

Is there a way to convert a Clojure form to a string? E.g. convert:

(and (f 1) (g 3))

to:

"(and (f 1) (g 3))"

Upvotes: 3

Views: 370

Answers (3)

paul
paul

Reputation: 1705

You can do this:

(str '(and (f 1) (g 3)))

EDIT

In case you're not familiar with it, the ' ("quote") character is a reader macro character (more) that escapes code -- i.e. keeps it from being evaluated.

You could also set a variable:

(def x '(and (f 1) (g 3)))
(str x)

and then if you wanted to run the code you could eval it.

Upvotes: 3

Suleymanoglu Naim
Suleymanoglu Naim

Reputation: 191

Alternativly if you don't know the form before hand you can do,

(defmacro to-str [f]
  (str f))

(to-str (and (f 1) (g 3)))

and get,

"(and (f 1) (g 3))"

Upvotes: 3

OpenSauce
OpenSauce

Reputation: 8623

=> (defmacro string-it [x] (str x))
#'user/string-it
=> (string-it (+ 1 2))
"(+ 1 2)"

Upvotes: 8

Related Questions