Forked from ertugrulcetin/if-let-multi-and-when-let-multi.clj
Created
June 30, 2017 21:29
-
-
Save kernelp4nic/c743ca800b6815af301aec19c80a5821 to your computer and use it in GitHub Desktop.
This file contains 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 assert-all | |
[& pairs] | |
`(do (when-not ~(first pairs) | |
(throw (IllegalArgumentException. | |
(str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form)))))) | |
~(let [more (nnext pairs)] | |
(when more | |
(list* `assert-all more))))) | |
(defmacro when-let* | |
"Multiple binding version of when-let" | |
[bindings & body] | |
(when (seq bindings) | |
(assert-all | |
(vector? bindings) "a vector for its binding" | |
(even? (count bindings)) "exactly even forms in binding vector")) | |
(if (seq bindings) | |
`(when-let [~(first bindings) ~(second bindings)] | |
(when-let* ~(vec (drop 2 bindings)) ~@body)) | |
`(do ~@body))) | |
;;Example when-let* | |
(when-let* [a 1 | |
b 2 | |
c (+ a b)] | |
(println "yeah!") | |
c) | |
;;=>yeah! | |
;;=>3 | |
(when-let* [a 1 | |
b nil | |
c 3] | |
(println "damn! b is nil") | |
a) | |
;;=>nil | |
(defmacro if-let* | |
"Multiple binding version of if-let" | |
([bindings then] | |
`(if-let* ~bindings ~then nil)) | |
([bindings then else] | |
(when (seq bindings) | |
(assert-all | |
(vector? bindings) "a vector for its binding" | |
(even? (count bindings)) "exactly even forms in binding vector")) | |
(if (seq bindings) | |
`(if-let [~(first bindings) ~(second bindings)] | |
(if-let* ~(vec (drop 2 bindings)) ~then ~else) | |
~(if-not (second bindings) else)) | |
then))) | |
;;Example if-let* | |
(if-let* [a 1 | |
b (+ a 1) ] | |
b) | |
;;=> 2 | |
(if-let* [a 1 | |
b (+ a 1) | |
c false] ;;false or nil - does not matter | |
b | |
a) | |
;;=> 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment