Skip to content

Instantly share code, notes, and snippets.

@MayDaniel
Forked from zk/check-let.clj
Created December 5, 2010 20:56
Show Gist options
  • Save MayDaniel/729458 to your computer and use it in GitHub Desktop.
Save MayDaniel/729458 to your computer and use it in GitHub Desktop.
(defmacro check-let [bindings & body]
(assert (vector? bindings))
(if (not-empty bindings)
(let [[binding [else & more]] ((juxt take drop) 2 bindings)]
`(if-let [~@binding] (check-let [~@more] ~@body) ~else))
`(do ~@body)))
(defmacro check-let [bindings & body]
(assert (vector? bindings))
(if (not-empty bindings)
(let [[binding [else & more]] (split-at 2 bindings)]
`(if-let [~@binding] (check-let [~@more] ~@body) ~else))
`(do ~@body)))
;; turns this:
(if-let [a 1]
(if-let [b 2]
(if-let [c 3]
(if-let [d 4]
{:success true :result (+ a b c d)}
{:success false :message "Couldn't find D"})
{:success false :message "Couldn't find C"})
{:success false :message "Couldn't find B"})
{:success false :message "Couldn't find A"})
;; into this:
(check-let [a 1 {:success false :message "Couldn't find A"}
b 2 {:success false :message "Couldn't find B"}
c 3 {:success false :message "Couldn't find C"}
d 4 {:success false :message "Couldn't find D"}]
{:success true :result (+ a b c d)})
;;
;; real world example: web request handler that inserts a new record
;;
;; this:
(defn new-addition [thought-id]
(fn [req]
(if-let [addition-text (:comment (:params req))]
(if-let [thought (find-thought! thought-id)]
(if-let [user (current-user! req)]
(let [addition (make-addition addition-text thought user)]
(insert! :additions addition)
(json-success (merge addition {:html (render-addition addition)})))
(json-fail "No valid user."))
(json-fail "No thought by that id."))
(json-fail "Text can't be blank."))))
;; into this:
(defn new-addition [thought-id]
(fn [req]
(check-let [addition-text (:comment (:params req)) (json-fail "Text can't be blank.")
thought (find-thought! thought-id) (json-fail "No thought by that id.")
user (current-user! req) (json-fail "No valid user.")]
(let [addition (make-addition addition-text thought user)]
(insert! :additions addition)
(json-success addition)))))
@zk
Copy link

zk commented Dec 7, 2010

Nice, mind if I steal this?

@MayDaniel
Copy link
Author

Sure. You're welcome to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment