2016-05-16 75 views
-2

我在验证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很陌生,仍然在努力学习它的基础知识。

谢谢,

回答

2

欢迎来到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"}}}) 

我希望帮助。

+0

感谢您的回复,但我仍然无法解决问题。请你能告诉我,条件类型需要什么类型的结构化输入。如何在条件语句中选择mytype1。 – peejain

+0

使用'conditional',每个子句按顺序进行评估。在你的例子中,%的值将为: {“mytype1”{“type”“string”}} 请注意,该值没有键':type',即使它有':type 'map to''string“'而不是''mytype”'。 – bbrinck