2015-12-11 28 views
1

我试图使用棱柱型模式来强制地图(1.0.4)棱镜模式强制 - 重命名映射键

我试图强迫

{:a 1} 

{:b 1} 

使用架构的自定义匹配器:

{:b s/Int} 

但这个代码不工作:

(require '[schema.core :as s]) 
(require '[schema.coerce :as coerce]) 

((coerce/coercer {:b s/Int} 
       (fn [s] 
        (when (= s s/Keyword) 
        (fn [x] 
         (if (= x :a) 
         :b 
         x))))) 
{:a 1}) 

输出:

#schema.utils.ErrorContainer{:error {:b missing-required-key, :a disallowed-key}} 

我试图通过运行在模式相匹配的一切,输出的电流值和模式相匹配下面的代码调试它:

((coerce/coercer {:b s/Int} 
      (fn [s] 
       (when true 
       (fn [x] 
        (println s x) 
        x)))) 
    {:a 1}) 

输出:

{:b Int} {:a 1} 
=> 
#schema.utils.ErrorContainer{:error {:b missing-required-key, :a disallowed-key}} 

看起来好像匹配器一到达地图就炸毁了?

回答

3

模式首先将您的地图分成符合模式的部分,然后将每个MapEntry强制为相应的MapEntry模式,依此类推。这种故障在你的情况下失败,所以你永远不会得到钥匙。

要完成你想要的任务,你必须将强制附加到地图模式并使用例如clojure.set/rename-keys您的强制功能:

(def Foo {:b s/Int}) 
((coerce/coercer 
    Foo 
    (fn [s] 
    (when (= s Foo) 
     #(clojure.set/rename-keys % {:a :b})))) 
{:a 1})