Clojure - build condp from vector hashmap

I would like to build a dynamic condp from a hashmap. I have the following structure: [{: value 50: ret "value50"} {: value 100: ret "value100}]

I would like to create a dynamic dynamic outline:

(condp < n
50 "value50"
100 "value100"
"default")

      

Should I use a macro to create this expression?

+3


source to share


2 answers


Yes. The macro will create the correct shape for you.

(defmacro mycondp
  [pred expr coll]
  `(condp ~pred ~expr
     ~@(mapcat (juxt :value :ret) coll)
     "default"))

      



Example:

(macroexpand-1 '(mycondp < n [{:value 50 :ret "value50"}]))
;; => (clojure.core/condp < n 50 "value50" "default")

      

+2


source


from (doc condp)

=>

... For each clause, (pred test-expr expr) is evaluated. If it returns logical true, the clause is a match. ...

This means, on average, you will have m / 2 comparisons, where m is the number of entries in your hashmap, so you can find the best solution if performance matters in your scenario.



Anyway, you have an alternative solution, I am not saying that this is more efficient, just a little easier to read for an average coder like myself

(def n 90)
(def clauses (hash-map 50 "value50", 100 "value100"))
(get clauses (first (filter #(< n %) (sort (keys clauses)))) "default")

      

Edited to ensure an orderly evaluation of proposals

+3


source







All Articles