开发者

Can I add fields to clojure types?

开发者 https://www.devze.com 2022-12-23 04:53 出处:网络
Clojure structs can be arbitrarily extended, adding new fields. Is it possible to extend types (created using deftype) in a similar way?

Clojure structs can be arbitrarily extended, adding new fields.

Is it possible to extend types (created using deftype) in a similar way?

EDIT: For the benefit future visitors, as Brian pointed out below, this feature is 开发者_如何学Csubject to change.


Actually you can treat types as maps, you just need to extend clojure.lang.IPersistentMap (an implementation is magically supplied).

(deftype A [a b]
  clojure.lang.IPersistentMap)
(A 1 2) ;; => #:A{:a 1, :b 2}
(assoc (A 1 2) :c 3) ;; => #:A{:a 1, :b 2, :c 3}

Note

Clojure has since split the semantics of types into defrecord and deftype. For most application-level programming, you'll want to use records. Conveniently, they automatically provide an implementation of clojure.lang.IPersistentMap, no magic necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消