Poor Man’s Tuples in Clojure
Hiredman is working on a nice implementation of tuples in Clojure. But, just for fun, I wanted to whip up the absolute minimum viable O(1) tuple possible.
The result is this macro:
(defmacro tuple
[& xs]
`(fn [idx#] (case idx# ~@(mapcat list (range (count xs)) xs))))
Try that in Ruby or C# ;)
So, (tuple "foo" 5 :bar) returns a function that takes an index and returns the value at that index in the arguments to tuple, i.e. ((tuple "foo" 5 :bar) 1) returns 5.
The macro compiles to a case form which dispatches in constant time, although it’s not as fast as Hiredman’s implementation, or even Clojure’s native vector.