2016-05-16 73 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