Guest User

Untitled

a guest
Jul 16th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. (defmacro check-let [b-vec & body]
  2. (if-not (empty? b-vec)
  3. (let [v (take 3 b-vec)
  4. r (apply vector (drop 3 b-vec))]
  5. `(if-let [~@(take 2 v)]
  6. (check-let ~r ~@body)
  7. ~(nth v 2)))
  8. `(do ~@body)))
  9.  
  10. ;; turns this:
  11.  
  12. (if-let [a 1]
  13. (if-let [b 2]
  14. (if-let [c 3]
  15. (if-let [d 4]
  16. {:success true :result (+ a b c d)}
  17. {:success false :message "Couldn't find D"})
  18. {:success false :message "Couldn't find C"})
  19. {:success false :message "Couldn't find B"})
  20. {:success false :message "Couldn't find A"})
  21.  
  22. ;; into this:
  23.  
  24. (check-let [a 1 {:success false :message "Couldn't find A"}
  25. b 2 {:success false :message "Couldn't find B"}
  26. c 3 {:success false :message "Couldn't find C"}
  27. d 4 {:success false :message "Couldn't find D"}]
  28. {:success true :result (+ a b c d)})
  29.  
  30.  
  31.  
  32. ;;
  33. ;; real world example: web request handler that inserts a new record
  34. ;;
  35.  
  36.  
  37. ;; this:
  38.  
  39. (defn new-addition [thought-id]
  40. (fn [req]
  41. (if-let [addition-text (:comment (:params req))]
  42. (if-let [thought (find-thought! thought-id)]
  43. (if-let [user (current-user! req)]
  44. (let [addition (make-addition addition-text thought user)]
  45. (insert! :additions addition)
  46. (json-success (merge addition {:html (render-addition addition)})))
  47. (json-fail "No valid user."))
  48. (json-fail "No thought by that id."))
  49. (json-fail "Text can't be blank."))))
  50.  
  51. ;; into this:
  52.  
  53. (defn new-addition [thought-id]
  54. (fn [req]
  55. (check-let [addition-text (:comment (:params req)) (json-fail "Text can't be blank.")
  56. thought (find-thought! thought-id) (json-fail "No thought by that id.")
  57. user (current-user! req) (json-fail "No valid user.")]
  58. (let [addition (make-addition addition-text thought user)]
  59. (insert! :additions addition)
  60. (json-success addition)))))
Add Comment
Please, Sign In to add comment