gpt4 book ai didi

Clojure.spec "or"相当于 "s/and"

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

我很喜欢使用 clojure.spec;它有助于发现更接近原因的数据错误。目前我正在使用它来验证对 Web 服务器请求的响应,但我在 clojure.spec 操作的语法上遇到了困难,该操作允许两种不同的 map 结构响应。

在我的数据中,网络服务器请求有两种可能的响应:

{:assignment "1232123"}

{:no-more-assignments true}

我可以使用 multi-spec,但这对于一些简单的事情来说似乎很冗长,例如为每种情况使用一个规范并将规范定义为:

(s/def ::response
(s/or ::case-1 ::case-2))

是否有一些我忽略的语法或者我需要使用 multi-spec

最佳答案

您可以将 orandkeys 规范一起使用:

(s/def ::assignment string?)
(s/def ::no-more-assignments boolean?)
(s/def ::response
(s/keys :req-un [(or ::assignment ::no-more-assignments)]))

(s/explain ::response {:assignment "123"})
;; Success!
(s/explain ::response {:foo true})
;; val: {:foo true} fails spec: :sandbox.so/response predicate: (or (contains? % :assignment) (contains? % :no-more-assignments))

关于Clojure.spec "or"相当于 "s/and",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203038/

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