Wednesday, November 22, 2023

Clojure 取代 if 的技巧 (3) --- Atom validator

;; Using :validator to replace the `if`
(def a 
  (atom 3 :validator pos?))

(swap! a dec)

;; Without using `:validator`, we need to put a `if`
(def b
  (atom 3))

(swap! b (fn [n]
           (if (pos? (dec n))
             (dec n)
             (throw (ex-info "content must be positive"
                             {:a 1})))))