gpt4 book ai didi

Clojure.spec key : separating key name from the spec validating it

转载 作者:行者123 更新时间:2023-12-04 05:11:44 25 4
gpt4 key购买 nike

我需要验证已从 json 字符串转换的 clojure 映射的形状。 json 字符串是我正在实现的协议(protocol)的消息。
为此,我正在尝试 clojure.spec.alpha。

我正在使用 s/keys。我的多条消息
协议(protocol)具有相同的键名,但附加到这些键的值不同,因此它们不能通过相同的规范进行验证。

一个例子:

;; Here status should have the same key name, but their shape
;; is different. But definining another spec forces me to register it with a
;; different keyword, which breaks the "should have name 'status'" requirement.

(s/def ::a-message
(s/keys :req [::status]))

(s/def ::another-message
(s/keys :req [::status]))

我想我可以在不同的命名空间中定义 :status 规范,但这对我来说似乎有点矫枉过正。
毕竟这只是同一协议(protocol)中的不同消息,我只是有一些冲突。

(s/keys) 有没有办法分隔正在检查其存在的 key 的名称
来自验证它的规范的名称?

最佳答案

在规范中,限定关键字用于创建全局语义(通过规范),其名称是限定关键字。如果您使用具有不同语义的相同限定关键字,我会说您应该更改代码以使用不同的限定符 :ex1/status 和 :ex2/status 用于不同的语义。

如果您使用非限定关键字(来自 JSON 时并不罕见),您可以使用 s/keys:req-un将不同的规范映射到数据不同部分的相同非限定关键字。

(s/def :ex1/status string?)
(s/def :ex2/status int?)

(s/def ::a-message (s/keys :req-un [:ex1/status]))
(s/def ::another-message (s/keys :req-un [:ex2/status]))

(s/valid? ::a-message {:status "abc"}) ;; true
(s/valid? ::another-message {:status 100}) ;; true

关于Clojure.spec key : separating key name from the spec validating it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43863505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com