Clojure强制性关键字参数(Clojure Mandatory keyword argument)

编程入门 行业动态 更新时间:2024-10-12 01:21:57
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.

更多推荐

本文发布于:2023-07-19 06:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1174823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:强制性   关键字   参数   Clojure   keyword

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!