Indexed data structures in Clojure
When rumbling in the Java source codes of the Clojure language, I found the mysterious IndexedSeq interface. What is it good for?
Details
It provides the int index()
method for collections to return the current index of the sequence on them.
It extends ISeq
, Sequential
, Counted
interfaces and thus IPersistentCollection
and Seqable
too.
Usage
One can easily create a wrapper class that gives an indexed functionality to any collection. The following example does just that.
Testing
Conclusion
The function shown can be used to wrap sequencial objects in order to keep track of the current index during iteration. This is a simple solution that comes handy when you would need to use map-indexed
otherwise.