如果所有默认值都是“值”,并且函数处于尾位置,这将这样做
(defn set-defaults [v m f]
(or (get m v) (f v)))
(defn points [s]
(mapv read-string (clojure.string/split s #"[ ,]")))
(-> {:points "1,2,3,4"
:stroke \#
:font-size "none"}
(update :stroke set-defaults {nil :black "none" :black \# \#} keyword)
(update :fill set-defaults {nil "transparent" "none" "transparent" \# \#} keyword)
(update :points set-defaults {nil [] [] []} points)
(update :stroke-width set-defaults {nil 1.0} identity)
(update :stroke-dasharray set-defaults {nil []} points)
(update :font-size set-defaults {nil 10 "none" 10} identity)
(clojure.set/rename-keys {:stroke-dasharray :stroke-dash-array}))
;=>
{:points [1 2 3 4]
:stroke \#
:font-size 10
:fill "transparent"
:stroke-width 1.0
:stroke-dash-array []}
或者,如果任何默认值也可以是一个函数
(defn set-defaults2 [v m defaultf]
(let [f (get m v defaultf)]
(f v)))
(-> {}
(update :stroke set-defaults2 {nil (constantly :black)}))
当然,在`condp`中还有一个`>>`“功能”:[https://docs.clojure.org/clojure.core/condp#example-542692cbc026201cdc326be4](https://docs.clojure.org/clojure.core/condp#example-542692cbc026201cdc326be4)