Skip to content

Instantly share code, notes, and snippets.

@ichramm
Forked from cemerick/gist:3750288
Created April 28, 2020 13:31
Show Gist options
  • Save ichramm/e46440e3bdfe93a0859f67d9a766f046 to your computer and use it in GitHub Desktop.
Save ichramm/e46440e3bdfe93a0859f67d9a766f046 to your computer and use it in GitHub Desktop.
Extending defrecord types in Clojure
;; Records are just types that provide default implementations of certain
;; key interfaces that allow them to stand in for maps.
;; This set of interfaces/protocols is not closed though; you can certainly make them
;; useful in places where maps aren't, e.g. w/ sequential destructuring:
=> (defrecord Point [x y]
clojure.lang.Indexed
(nth [_ i] (case i 0 x 1 y
(throw (IndexOutOfBoundsException.))))
(nth [_ i default]
(case i 0 x 1 y
default)))
user.Point
=> (let [[a b] (Point. 1 2)]
(+ a b))
3
;; (Further examples can be found in http://clojurebook.com ;-)
;; The macro to generalize the above for records that define any number of slots
;; is fairly simple, and left as an exercise.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment