Creating code on the fly using Clojure eval
Code
;; defining_functions_on_the_fly.clj
(eval `(def x 1))
x
(def map-vals
{:a 10
:b 20
:c 30})
(doseq [[k v] map-vals]
(eval
`(defn ~(symbol k) []
~v)))
(a)
(b)
(c)
(def planets ["Earth" "Mars" "Venus" "Jupiter" "Saturn"])
;; Generate and define functions for each planet
(doseq [planet planets]
(eval
`(defn ~(symbol (str "hello-" (clojure.string/lower-case planet))) []
~(str "Hello " planet))))
;; Now you can call the generated functions:
(hello-earth) ; => "Hello Earth"
(hello-mars) ; => "Hello Mars"
(hello-venus) ; => "Hello Venus"Notes