Skip to content

Instantly share code, notes, and snippets.

@hugoduncan
Created November 29, 2012 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugoduncan/4169539 to your computer and use it in GitHub Desktop.
Save hugoduncan/4169539 to your computer and use it in GitHub Desktop.
Modified core threading macros
(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