Create optional fields on Clojure record?

为君一笑 提交于 2019-12-22 03:35:44

问题


When I instantiate a clojure record I get an error if I do not set all the fields of the record. How can I specify some of the fields to be optional?


回答1:


defrecord declares a type and a constructor, but the type implements the clojure map interface. You just need to put the required fields in the declaration. For example,

(defrecord MyRecord [required1 required2])

(defn make-my-record [r1 r2 & [opt1 opt2]]
  (assoc (MyRecord. r1 r2) :optional1 opt1 :optional2 opt2))

Can be used like,

user> (make-my-record 1 2)
#:user.MyRecord{:required1 1, :required2 2, :optional2 nil, :optional1 nil}
user> (make-my-record 1 2 :a :b)
#:user.MyRecord{:required1 1, :required2 2, :optional2 :b, :optional1 :a}


来源:https://stackoverflow.com/questions/4580606/create-optional-fields-on-clojure-record

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!