Skip to content

Instantly share code, notes, and snippets.

@lambder
Created March 1, 2011 14:10
Show Gist options
  • Save lambder/849175 to your computer and use it in GitHub Desktop.
Save lambder/849175 to your computer and use it in GitHub Desktop.
Clojure quivalent of ruby's andand. Threads the expr through the forms, short circuiting in case of falsey result
(defmacro &&>
"Clojure quivalent of ruby's andand. Threads the expr through the forms, short circuiting in case of falsey result.
Inserts x as the second item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
second item in second form, etc.
example:
(let [o {:a 123}]
(assert (= 124 (&&> o :a (+ 1))))
(assert (= nil (&&> o :a (+ 1) :c :b)))
(assert (= false (&&> false :a (+ 1) :c :b)))
(assert (= nil (&&> nil :a (+ 1) :c :b)))
)
"
([x] x)
([x form]
(let [result-sym (gensym "result-sym-")]
`(let [~result-sym ~x]
(if ~result-sym
~(if (seq? form)
(concat (list (first form)) (list result-sym) (next form))
(list form result-sym)
)
~result-sym
)))
)
([x form & more] `(&&> (&&> ~x ~form) ~@more)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment