/
control.cljc
55 lines (50 loc) · 1.78 KB
/
control.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
;; Copyright 2014 Timothy Dean
;; Copyright 2017-2018 Workiva Inc.
(ns humilia.control
"Control forms"
#?(:cljs (:require-macros humilia.control)))
#?(:clj
(defmacro ?->>
"Like cond->>, but threads the argument through the conditions as well.
(?->> 4 even? (assoc {} :four))"
[expr & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test step]] `(if (->> ~g ~test) (->> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g))))
#?(:clj
(defmacro ?->
"Like cond->, but threads the argument through the conditions as well.
(?-> 4 even? inc odd? inc neg? inc)"
[expr & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test step]] `(if (-> ~g ~test) (-> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g))))
#?(:clj
(defmacro ->>?->
"Like ?->, but the conditions are threaded with ->> and the results are
threaded with ->.
(->>?-> 4 (> 2) inc (> 6) dec)"
[expr & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test step]] `(if (->> ~g ~test) (-> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g))))
#?(:clj
(defmacro ->?->>
"Like cond->, but threads the argument through the conditions as well.
(->?->> 4 (> 2) inc (> 6) dec)"
[expr & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test step]] `(if (-> ~g ~test) (->> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g))))