如何在Clojure中为记录中的字段设置默认值?

Zub*_*air 14 clojure

我在Clojure中创建记录,并希望使用默认值设置一些字段.我怎样才能做到这一点?

kot*_*rak 22

使用构造函数.

(defrecord Foo [a b c])

(defn make-foo
  [& {:keys [a b c] :or {a 5 c 7}}]
  (Foo. a b c))

(make-foo :b 6)
(make-foo :b 6 :a 8)
Run Code Online (Sandbox Code Playgroud)

当然有各种各样的变化.例如,您可以要求某些字段是非可选字段而不是默认字段.

(defn make-foo
  [b & {:keys [a c] :or {a 5 c 7}}]
  (Foo. a b c))

(make-foo 6)
(make-foo 6 :a 8)
Run Code Online (Sandbox Code Playgroud)

因人而异.


mik*_*era 12

通过扩展映射构建初始值时,可以非常轻松地将初始值传递给记录:

(defrecord Foo [])

(def foo (Foo. nil {:bar 1 :baz 2}))
Run Code Online (Sandbox Code Playgroud)

鉴于此,我通常会创建一个构造函数,它合并一些默认值(您可以根据需要进行覆盖):

(defn make-foo [values-map]
  (let [default-values {:bar 1 :baz 2}]
    (Foo. nil (merge default-values values-map))))

(make-foo {:fiz 3 :bar 8})
=> #:user.Foo{:fiz 3, :bar 8, :baz 2}
Run Code Online (Sandbox Code Playgroud)