[英]Parsing with clojure.spec
(require '[clojure.spec :as s])
consider the following data: 考虑以下数据:
(def data {:names [["Anna" :lucky]
["Peter"]
["Jon" :lucky]
["Andre" :lucky]]})
It's a hash-map of with one key :names having a value of a vector of vectors. 它是一个带有一个键的哈希映射:具有向量向量值的名称。 The inner vectors must contain a string as the first element and can optionally contain a the keyword :lucky as the second element.
内部向量必须包含一个字符串作为第一个元素,并且可以选择包含关键字:lucky作为第二个元素。
The previous two sentences should be described with clojure.spec
- Let's start with the items in the vector: 前两个句子应该用
clojure.spec
来描述 - 让我们从向量中的项开始:
(s/def ::item (s/cat :name string? :lucky (s/? #(= :lucky %))))
(s/conform ::item ["Tom"])
;; {:name "Tom"}
(s/conform ::item ["Tom" :lucky])
;; {:name "Tom", :lucky :lucky}
(s/conform ::item ["Tom" :sad])
;; :clojure.spec/invalid
This works. 这有效。 However, if there is only one option.
但是,如果只有一个选项。 Wouldn't a parsed result look be better like this:
解析后的结果不会像这样更好:
`{:name "Tom", :lucky true}` or `{:name "Tom", :lucky false}`
Can this be done in clojure.spec? 这可以在clojure.spec中完成吗?
With this, one can carry on: 有了这个,人们就可以继续:
(s/def ::items (s/coll-of ::item '()))
(s/conform ::items [["Tom" :lucky] ["Tim"]])
[["Tom" :lucky] ["Tim"]]
However, it looks like it passes the test but why the items are not parsed anymore? 但是,看起来它通过了测试,但为什么这些项目不再被解析?
Edit: This could be solved by switching from alpha7 to alpha10 release, where coll-of only takes one argument 编辑: 这可以通过从alpha7切换到alpha10版本来解决,其中coll-of只接受一个参数
Finally my spec looks like, having the previously described caveats: 最后我的规范看起来像前面所述的警告:
(s/def ::my-spec (s/keys req-un [::items]))
spec is not designed to provide arbitrary data transformation (Clojure's core library can be used for that). spec不是为提供任意数据转换而设计的(Clojure的核心库可用于此)。
It is possible to achieve this using s/conformer
but it is not recommended to use that feature for arbitrary transformations like this (it is better suited to things like building custom specs). 可以使用
s/conformer
实现这一点,但不建议将此功能用于此类任意转换(它更适合构建自定义规范之类的东西)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.