Last active
July 6, 2019 20:27
-
-
Save mkwatson/ee50ce4df6b5f409ad87 to your computer and use it in GitHub Desktop.
while->
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 while-> | |
"Takes a predicate, expression, and forms. Threads expr | |
through each form for which applying pred to the returned | |
value is true. Threading short circuits after the first | |
false expression." | |
[pred expr & forms] | |
`(if (~pred ~expr) | |
~(if (not-empty forms) | |
(let [next-expr `(-> ~expr ~(first forms))] | |
`(if (~pred ~next-expr) | |
(while-> ~pred ~next-expr ~@(rest forms)) | |
~expr)) | |
expr))) | |
;; EXAMPLES | |
(while-> number? 3 (+ 2) (str " lemon") (+ 100)) ;=> 5 | |
(while-> number? 3 (+ 2) inc (* 100)) ;=> 600 | |
(while-> number? "Hello World!" first) ;=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO:
1 ) Check first (~pred ~expr) only once, then use loop/recur on an inner loop
2 ) Remove double eval of next-expr (in if condition and in recursive while-> call)