Michael <mw10...@gmail.com> writes:

> I'm trying to use << from clojure.contrib.strint perform string
> interpolation in a string variable.  The following,

> (def s "v: ~{v}")
> (println (<< (str s)))
> (println (<< s))

This is not going to be possible (at least not efficiently: you could
technically do itwith &env and eval, but it would be slow and ugly).
The << macro compiles the interpolation string into code, so it needs
access to the string at compile-time.

It also needs to capture "v" and you can't get lexical bindings at
run-time unless you explicitly hold onto them all with &env.  Capturing
the entire lexical environment is generally a bad idea (although useful
in a few specific cases like debug-repl) as it breaks local-clearing and 
could cause difficult to diagnose "holding onto head" problems.

You didn't explain why you wanted to do it.  Maybe you could pass around
first class functions instead of strings?

(def greetings
 {:english 
  (fn [m] (<< "Hello ~(:name m). You have ~(:balance m) dollars."))
  :german  
  (fn [m] (<< "Hallo ~(:name m). Sie haben ~(:balance m) dollar."))})

(def *lang* :english)

(println ((greetings *lang*) {:name "John", :balance 200}))


Personally I'm not a fan of the << style string interpolation (at least
in Clojure where there's better options).  I think #'format is generally
a better choice for this sort of thing and since it can't contain
arbitrary Clojure code it doesn't need to be compiled:

(def *lang* :german)

(def greetings
 {:english "Hello %s.  You have %d dollars."
  :german "Hallo %s.  Sie haben %d dollar."})

(format (greetings *lang*) "John" 200)

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to