Skip to content

Instantly share code, notes, and snippets.

@fogus
Forked from richhickey/thread.clj
Created October 15, 2012 13:45
Show Gist options
  • Save fogus/3892535 to your computer and use it in GitHub Desktop.
Save fogus/3892535 to your computer and use it in GitHub Desktop.
new thread macros draft
(defmacro test->
"Takes an expression and a set of test/form pairs. Threads expr (via ->)
through each form for which the corresponding test is true."
[expr
& clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test step]] `(if ~test (-> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g)))
(defmacro test->>
"Takes an expression and a set of test/form pairs. Threads expr (via ->>)
through each form for which the corresponding test is true."
[expr & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test step]] `(if ~test (->> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g)))
(defmacro let->
"Binds name to expr, evaluates the first form in the lexical context
of that binding, then binds name to that result, repeating for each
successive form"
[expr name & forms]
`(let [~name ~expr
~@(interleave (repeat name) forms)]
~name))
(defmacro when->
"When expr is logical true, threads it into the first form (via ->),
and when that result is logical true, through the next etc"
[expr & forms]
(let [g (gensym)
pstep (fn [step] `(when ~g (-> ~g ~step)))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep forms))]
~g)))
(defmacro when->>
"When expr is logical true, threads it into the first form (via ->>),
and when that result is logical true, through the next etc"
[expr & forms]
(let [g (gensym)
pstep (fn [step] `(when ~g (->> ~g ~step)))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep forms))]
~g)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment