Created
November 29, 2012 14:48
-
-
Save hugoduncan/4169539 to your computer and use it in GitHub Desktop.
Modified core threading macros
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 when-> | |
"When expr is logical true, threads it into the first form (via ->), | |
and when that result is logical true, through the next etc" | |
{:added "1.5"} | |
[expr & forms] | |
(let [[g forms] (if (vector? (first forms)) | |
[(ffirst forms) (rest forms)] | |
[(gensym) forms]) | |
pstep (fn [step] `(when ~g (-> ~g ~step)))] | |
`(let [~g ~expr | |
~@(interleave (repeat g) (map pstep forms))] | |
~g))) | |
;; (when-> 1 [a] | |
;; (+ a 2) | |
;; (+ a 3) | |
;; (- a 6)) | |
;; => -6 | |
(defmacro test-> | |
"Takes an expression and a set of test/form pairs. Threads expr (via ->) | |
through each form for which the corresponding test expression (not threaded) is | |
true." | |
[expr & clauses] | |
(let [[g clauses] (if (vector? (first clauses)) | |
[(ffirst clauses) (rest clauses)] | |
[(gensym) clauses]) | |
pstep (fn [[test step]] `(if ~test (-> ~g ~step) ~g))] | |
(assert (even? (count clauses))) | |
`(let [~g ~expr | |
~@(interleave (repeat g) (map pstep (partition 2 clauses)))] | |
~g))) | |
;; (test-> 1 [a] | |
;; (= a 1) (+ 2) | |
;; (= a 3) (+ 3) | |
;; (= a 6) (+ 1)) | |
;; => 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment