Clojure: Idiomatic (when (predicate x) x)

In the same way, you can convert

(if (something)
    something
    fallback)

      

into a shorter version:

(or something fallback)

      

I was wondering if there is a composition function / elegant built in to stream the value into a predicate check like:

(when (pred x)
  x)

      

In something like

(thread-pred pred x)

      

I could easily create some function or macro to do this, but I wouldn't NIH here.

+3


source to share


1 answer


It took me longer than I'd like to admit - but here you go:

Beware that it could explode.

(defmacro -pred-> 
  [pred body] 
  `(when (~pred ~body) ~body))

(macroexpand-1 '(-pred-> odd? 3))
=> (clojure.core/when (odd? 3) 3)

(-pred-> odd? 3)
=> 3

(-pred-> odd? 2)
=> nil

      




EDIT: Since the comments correctly indicate that it would be wiser to link the body to an autogenous way:

(defmacro -pred-> 
  [pred body] 
  `(let [b# ~body] 
     (when (~pred b#) b#)))

      

0


source







All Articles