clojure - Required keys when destructuring -
is there way have exception raised if keys you're trying destructure aren't in map passed function? use case macro?
for example:
(defn x [{:keys [a b]}] (println b))
i'd work:
(x {:a 1 :b 2})
but raise exception (:b missing)
(x {:a 1})
what pre-condition?
(defn x [{:keys [a b]}] {:pre [(some? a) (some? b)]} (println b)) user=> (x {:a 1}) assertionerror assert failed: (some? b) user/x (no_source_file:1) edit: yes, use macro handle you. maybe this:
(defmacro defnkeys [name bindings & body] `(defn ~name [{:keys ~bindings}] {:pre ~(vec (map #(list 'some? %) bindings))} ~@body)) (defnkeys foo [a b] (println b)) (foo {:a 1 :b 2}) (foo {:a 1}) ;; assertionerror assert failed: (some? b) (foo {:a 1 :b nil}) ;; assertionerror assert failed: (some? b)
Comments
Post a Comment