On Mar 31, 2014, at 1:27 PM, A. Webb <a.webb....@gmail.com> wrote: > > If you are working with quoted expressions, you'll have to eval in the macro > and take the one-time hit there > > (defmacro functionalise2 > [ex var] > (let [arg (gensym) > body (clojure.walk/postwalk-replace {var arg} ex)] > `(fn [~arg] ~(eval body)))) > > (def foo2 (functionalise2 '(+ 2 x) x)) > (foo2 40) ;=> 42 >
Or if the reason that you're quoting is because that's a stand-in for an expression that will be generated dynamically then maybe you don't want to do it in a macro, but instead call eval on function-defining expression that includes your expression and takes an argument for the variable. Easier shown than said: (defn functionalise [ex var] (eval (list 'fn (vector var) ex))) (def ex '(+ 1 x)) (def exf (functionalise ex 'x)) (exf 3) ;; => 4 This calls eval only once when you call functionalise, and doesn't do any tree walking. FWIW this is the trick I use in the tiny genetic programming system at: https://github.com/lspector/gp/blob/master/src/gp/evolvefn.clj -Lee -- 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 --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.