Last active
September 9, 2015 14:31
-
-
Save kendagriff/b39d28e2179cf56d8234 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-> | |
"As long as the predicate holds true, threads | |
the expr through each form (via `->`). Once pred returns | |
false, the current value of all forms is returned." | |
[pred expr & forms] | |
(let [g (gensym) | |
pstep (fn [step] `(if (~pred ~g) (-> ~g ~step) ~g))] | |
`(let [~g ~expr | |
~@(interleave (repeat g) (map pstep forms))] | |
~g))) | |
(defn valid? [v] | |
(not (contains? v :errors))) | |
(while-> valid? | |
{:hello "world"} | |
(assoc :errors "my errors") | |
(assoc :and "goodbye")) | |
;; => {:hello "world", :errors "my errors"} | |
(while-> valid? | |
{:hello "world"} | |
(assoc :and "goodbye")) | |
;; => {:hello "world" :and "goodbye"} |
Interesting. This seems like a generalization of some->
, but that fact doesn't seem useful.
You'll want to gensym and let-bind pred
because it could be a computed value.
Ah, good point. I'll make that change...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was looking for a way to pass an expression to a pipeline of functions and, given a predicate function, only spit out the final answer should the predicate hold true all the way through. If not, spit out the return value at the form expression that returned false.
As shown in the example, my use case was wanting a simple way of bailing execution should a validation error arise, without
if
logic.