Skip to content

Instantly share code, notes, and snippets.

@wwiill
Created October 6, 2020 11:04
Show Gist options
  • Save wwiill/43e59409e79b605e93ab16064468a018 to your computer and use it in GitHub Desktop.
Save wwiill/43e59409e79b605e93ab16064468a018 to your computer and use it in GitHub Desktop.
Unless error macro
(defmacro unless-error->
"Unless expr is a map like {:error xxx}, threads it into the first form (via ->),
and unless that result is a map like {:error xxx}, through the next etc"
[expr & forms]
(let [g (gensym)
steps (map (fn [step] `(if (:error ~g) ~g (~step ~g)))
forms)]
`(let [~g ~expr
~@(interleave (repeat g) (butlast steps))]
~(if (empty? steps)
g
(last steps)))))
(defn boo [x]
(println "boo:" x)
{:error "boo"})
(defn foo [x]
(println "foo:" x)
(:name x))
(defn moo [x]
(println "moo:" x)
(str/upper-case x))
(unless-error-> {:name "trump"} foo boo moo)
(unless-error-> {:name "trump"}
foo
(fn [x] x)
moo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment