Code Aquarium

minazoko's blog -*- 水底のブログ -*-

ぼくのかんがえたスレッディングマクロ

cond-> も as-> みたいにシンボルを指定できたらいいと思いました。

(defmacro cond-as-> [init name & forms]
  (when-not (even? (count forms))
    (throw (IllegalArgumentException. "require an even number of forms")))
  (if-not forms
    init
    `(let [~name ~init
           ~@(->> forms
                  (drop-last 2)
                  (partition 2)
                  (mapcat (fn [fms] `(~name (if ~@fms ~name)))))]
       (if ~@(take-last 2 forms) ~name))))

用例

(cond-as-> 10 x
           (even? x) (/ x 2)
           (odd?  x) (-> (* 3 x) inc)
           (even? x) (/ x 2)
           (odd?  x) (-> (* 3 x) inc))
;;=> 8

どない?