open:thread-cond

cond->

;; Don't
(let [x (if (p0 x) (f0 x) x)
      x (if (p1 x) (f1 x) x)]
  (if (p2 x) (f2 x) x))
 
;; Do
(cond-> x
  (p0 x) f0
  (p1 x) f1
  (p2 x) f2)

(defmacro cond*->
  [expr & clauses]
  (assert (even? (count clauses)))
  (let [g (gensym)
        steps (map (fn [[test step]] `(if (-> ~g ~test) (-> ~g ~step) ~g))
                   (partition 2 clauses))]
    `(let [~g ~expr
           ~@(interleave (repeat g) (butlast steps))]
       ~(if (empty? steps)
          g
          (last steps)))))
 
(cond*-> x
         p0 f0
         p1 f1
         p2 f2)


  • open/thread-cond.txt
  • 마지막으로 수정됨: 2022/03/08 00:17
  • 저자 127.0.0.1