I would like to create a factory, in clojure where the number of arguments to the creator varies at run time.
For example:
(defn create-long-document [direction]
(str "long document " direction))
(defn create-short-document[]
"short document")
(def creator-map {
:english create-short-document
:hebrew create-long-document
})
(def additional-arg-map {
:english nil
:hebrew "rtl"
})
(defn create-document [language]
(let [creator (language creator-map) arg (language additional-arg-map)]
(if arg (creator arg) (creator))))
(println (create-document :hebrew)); long document rtl
(println (create-document :english)); short document
I am looking for an elegant way to rewrite the body of create-document. I want to get rid of the if. Maybe by introducing a smart macro?
Please share you ideas.
I’d suggest having your additional arguments specified as collections:
Then you can use apply in your create-document function, something like:
Note that an alternative (or perhaps complementary?) approach would be to define a variable-arity function if you want to allow the caller to provide specific extra arguments, e.g. something like: