mardi 8 août 2017

Clojure default value with predicate

A common pattern is to provide a default value if some value does not fulfill a predicate. What is a good way of writing such a pattern when the value is not bound to a name?

Currently I use a let expression. If for example I would like to provide a default value for empty strings I might write something like:

(let [value {:a "foo"}]
  (if (:a value) value {:a "bar"})) 

However, I feel like this could be simplified to closer match the same proceduce for falsy values.

(or value default)

I have considered creating a function that does it:

(defn or-default [pred value default]
  (if (pred value) value default))

With which the above example would become:

(or-default :a {:a "foo"} {:a "bar"})

However I assume someone must have thought about this earlier, so is there an established way?

Aucun commentaire:

Enregistrer un commentaire