Clojure 规范强制嵌套映射值
Clojure spec coerce nested map value
我像这样强制映射值:
(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"}}
代替更好吗?
(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}}
我像这样强制映射值:
(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"}}
代替更好吗?
(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}}