Yeonho
Yeonho

Reputation: 3623

Idiomatic way to return value if test succeeds or return default in Clojure

What's the idiomatic way to return value only if test succeeds, and return default otherwise? I suppose it's trivial to build one, but I wanted to know if there was a built-in function for that purpose.

(def a {:name "foo"})
(if (map? a) a {})
; {:name "foo"}

(def b "bar")
(if (map? b) b {})
; {}

; is there a built-in function that looks like this?
(get-if map? b {})

Upvotes: 1

Views: 94

Answers (2)

OlegTheCat
OlegTheCat

Reputation: 4513

Usually it is preferable to use functions instead of macros if it is possible:

(defn get-if [pred v default]
  (if (pred v) v default))

Upvotes: 2

Marcin Bilski
Marcin Bilski

Reputation: 611

The macro is pretty trivial to write. I don't believe this is idiomatic in that it adds an extra layer of abstraction without increasing readability. Someone reading a code like that has to look at the macro to figure out what is going on as opposed to a simple if.

The macro:

(defmacro get-if
  [p v d]
  `(let [val# ~v]
     (if (~p val#)
       val#
       ~d)))

Perhaps if you tell more about what is your use case I can help you more?

Upvotes: 1

Related Questions