Skip to content

Instantly share code, notes, and snippets.

@sjl
Forked from cemerick/gist:3750288
Created September 19, 2012 16:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sjl/3750572 to your computer and use it in GitHub Desktop.
Save sjl/3750572 to your computer and use it in GitHub Desktop.
defrec, rhymes with vec, because you can nth it
(defmacro defrec [name args & body]
(let [indexed-args (interleave (iterate inc 0) args)]
`(defrecord ~name ~args
clojure.lang.Indexed
(nth [_# i#]
(case i#
~@indexed-args
(throw (IndexOutOfBoundsException.))))
(nth [_# i# default#]
(case i#
~@indexed-args
default#))
~@body)))
(defrec Point [x y])
(let [p (->Point 10 20)
[x y] p]
(println y x))
;=> 20 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment