Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default values for fields in records in Clojure?

Tags:

clojure

I am creating records in Clojure and would like to set some fields up with a default value. How can I do this?

like image 694
yazz.com Avatar asked Apr 12 '11 11:04

yazz.com


Video Answer


2 Answers

Use a constructor function.

(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)

Of course there are various variations. You could for example require certain fields to be non-optional and without a default.

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

(make-foo 6)
(make-foo 6 :a 8)

YMMV.

like image 50
kotarak Avatar answered Oct 03 '22 00:10

kotarak


You can pass initial values to a record pretty easily when you construct it though an extension map:

(defrecord Foo [])

(def foo (Foo. nil {:bar 1 :baz 2}))

In light of this, I usually create a constructor function that merges in some default values (which you can override as you want):

(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}
like image 26
mikera Avatar answered Oct 02 '22 23:10

mikera