Clojure spec强制嵌套地图值

时间:2016-07-17 23:27:37

标签: clojure clojure.spec

我强制执行这样的地图值:

(require '[clojure.spec :as s])

(defn x-integer? [x]
  (cond
    (integer? x) x
    (string? x) (try
                  (Integer/parseInt x)
                  (catch Exception e
                    :clojure.spec/invalid))
    :else :clojure.spec/invalid))

(s/def ::port (s/conformer x-integer?))

(s/def ::config (s/keys :req [::port]))

(s/conform ::config {::port "12345"}) ;;=> #:my.ns{:port "12345"}

但是我不知道如何用以下地图做同样的事情:

(s/conform ::config {::nested-data {:port "12345"}}) ;;=> something like that maybe ? #:my.ns/nested-data{:port 12345}

如何定义::config?另外,最好是{::nested-data {::port "12345"}}代替吗?

1 个答案:

答案 0 :(得分:9)

(s/def ::port (s/conformer x-integer?))
(s/def ::nested-data (s/keys :req-un [::port]))
(s/def ::config (s/keys :req [::nested-data]))
(s/conform ::config {::nested-data {:port "12345"}})
;;=> #:spec.examples.guide{:nested-data {:port 12345}}