Skip to content

Instantly share code, notes, and snippets.

@mkwatson
Last active July 6, 2019 20:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkwatson/ee50ce4df6b5f409ad87 to your computer and use it in GitHub Desktop.
Save mkwatson/ee50ce4df6b5f409ad87 to your computer and use it in GitHub Desktop.
while->
(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
@mkwatson
Copy link
Author

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)

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