如果您尝试解构的键不在传递给您的函数的地图中,是否有办法引发异常?这对宏来说是一个很好的用例吗?
例如:
(defn x [{:keys [a b]}] (println a b))
我希望这项工作:
(x {:a 1 :b 2})
但这会引发异常(:b缺失)
(x {:a 1})
答案 0 :(得分:5)
pre-condition怎么样?
(defn x [{:keys [a b]}]
{:pre [(some? a) (some? b)]}
(println a b))
user=> (x {:a 1})
AssertionError Assert failed: (some? b) user/x (NO_SOURCE_FILE:1)
编辑:是的,您可以使用宏来为您处理此问题。也许是这样的:
(defmacro defnkeys [name bindings & body]
`(defn ~name [{:keys ~bindings}]
{:pre ~(vec (map #(list 'some? %) bindings))}
~@body))
(defnkeys foo [a b]
(println a b))
(foo {:a 1 :b 2})
(foo {:a 1}) ;; AssertionError Assert failed: (some? b)
(foo {:a 1 :b nil}) ;; AssertionError Assert failed: (some? b)