clojure模式的验证



我在验证clojure棱柱模式时遇到了一个问题。这是代码。

:Some_Var1 {:Some_Var2  s/Str
                  :Some_Var3 ( s/conditional
                        #(= "mytype1" (:type %)) s/Str
                        #(= "mytype2" (:type %)) s/Str
                  )}

我正在尝试使用以下代码进行验证:

"Some_Var1": {
    "Some_Var2": "string",
"Some_Var3": {"mytype1":{"type":"string"}}
  }

但它给了我一个错误:

{
  "errors": {
    "Some_Var1": {
      "Some_Var3": "(not (some-matching-condition? a-clojure.lang.PersistentArrayMap))"
    }
  }
}

这是我正在尝试验证的一个非常基本的代码。我是clojure的新手,仍在努力学习它的基础知识。

谢谢,

欢迎使用Clojure!这是一门很棒的语言。

在Clojure中,关键字和字符串是不同的类型,即:type"type"不同。例如:

user=> (:type  {"type" "string"})
nil
(:type  {:type "string"})
"string"

然而,我认为这里还有一个更深层次的问题:从你的数据来看,你似乎想在数据本身中编码类型信息,然后根据这些信息进行检查。这可能是可能的,但这将是一种相当高级的模式用法。模式通常用于在类型之前已知类型的情况,例如:等数据

(require '[schema.core :as s])
(def data
  {:first-name "Bob"
   :address {:state "WA"
             :city "Seattle"}})
(def my-schema
  {:first-name s/Str
   :address {:state s/Str
             :city s/Str}})
(s/validate my-schema data)

我建议,如果您需要基于编码的类型信息进行验证,那么为其编写自定义函数可能会更容易。

希望能有所帮助!

更新:

作为conditional如何工作的一个例子,这里有一个将进行验证的模式,但同样,这是模式的非惯用用法

(s/validate
{:some-var3
(s/conditional
 ;; % is the value: {"mytype1" {"type" "string"}}
 ;; so if we want to check the "type", we need to first
 ;; access the "mytype1" key, then the "type" key
 #(= "string" (get-in % ["mytype1" "type"]))
 ;; if the above returns true, then the following schema will be used.
 ;; Here, I've just verified that
 ;; {"mytype1" {"type" "string"}}
 ;; is a map with key strings to any value, which isn't super useful
 {s/Str s/Any}
)}
{:some-var3 {"mytype1" {"type" "string"}}})

我希望这能有所帮助。

最新更新