-
-
Save MayDaniel/729458 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure. You're welcome to.