Clojure强制性关键字参数(Clojure Mandatory keyword argument)
我有这样的功能:
(defn foo [{a :keya b :keyb}] (list a b))我这样称呼它:
(foo {:keya "hi"}) ; Returns ("hi" nil)如果我没有给出keyb关键字参数,那么它就是零。 有没有办法确保它为它抛出异常,而不是将它作为零。
(我知道我可以手动检查并抛出一个异常,但是是否有任何特殊的选项来强制约束。)
I have a function like this:
(defn foo [{a :keya b :keyb}] (list a b))And i'm calling it like this:
(foo {:keya "hi"}) ; Returns ("hi" nil)If I don't give keyb keyword argument, it takes nil for that. Is there a way to ensure that it throws exception for it instead of taking it as nil.
( I know that I can manually check and throw an exception, but is there any special option which enforces the constraints.)
最满意答案
您可以使用前提条件( http://clojure.org/special_forms#toc9 )来声明密钥存在:
(defn foo [{a :keya b :keyb}] {:pre [(not (nil? b))]} (list a b))当密钥为零时,这将引发一个AssertionError。
You can use a precondition (http://clojure.org/special_forms#toc9) to assert the key is present:
(defn foo [{a :keya b :keyb}] {:pre [(not (nil? b))]} (list a b))This will throw an AssertionError when the key is nil.
更多推荐
发布评论