Reputation: 18005
I am using a map to store function calls (in ClojureScript, but it should be the same in Clojure) :
(def parse-fn {:json js/JSON.parse
:edn read-string
:transit t->clj})
I then have a transform
function like the following :
(defn transform [format data]
((get parse-fn format) data))
Calling transform
like that : (transform :transit data)
works nicely. I am only worried about the readability of the transform
function. It is not immediately obvious that the first thing is a function.
Edit : I cannot just call (:transit parse-fn)
since the format
comes from another function, as in : (another-fn [... format ...] ... (transform format data))
Is there an explicit call
function, or is the structure of this code not idiomatic ?
Upvotes: 2
Views: 875
Reputation: 29999
Maybe consider treating the keyword as the function.
((:transit parse-fn) data)
To me the more terse approach helps me recognise the first element as distinct.
Alternatively, you can treat the map as the function instead.
((parse-fn :transit) data)
As I understand, the first approach is generally considered more idiomatic and it can also be optimized more intelligently.
Upvotes: 1
Reputation: 91567
Your initial design is completely readable. Passing functions to other functions that do the actual work is a fairly normal way of doing things. I don't think you need to change anything to "make it more readable". If i was going to change anything to make i more clrearly spelled out would be to change the name of transform to transform-lookup or get-transform
(another-fn [... format ...] ... (transform-lookup format data))
or
(another-fn [... format ...] ... (get-transform format data))
Though this is a very minor distinction and it's fine the way it is.
Upvotes: 1