Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Clojure: Converting a Custom Collection to a Sequence

DZone's Guide to

Clojure: Converting a Custom Collection to a Sequence

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

I've been doing a bit of clojure lately and I've often found myself looking to convert a custom collection to a sequence. Unfortunately, several custom collections from libraries that we use don't implement Iterable; therefore, I can't simply use the seq function to create a seq.

In Java it's common to simply use a for loop and a get method to iterate through custom collections that don't implement Iterable.

for (int i=0; i<fooCollection.size(); i++) {
Foo foo = fooCollection.get(i);
}
There are patterns for doing something similar in Clojure; however, I much prefer to work with Sequences and functions that operate on Sequences. Shane Harvie and I added the following snippet to our code to quickly convert a custom collection to a seq.
(defmacro obj->seq [obj count-method]
`(loop [result# []
i# 0]
(if (< i# (. ~obj ~count-method))
(recur (conj result# (.get ~obj i#)) (inc i#))
result#)))
Our first version only worked with a custom collection that had a .size() method; however, the second collection we ran into used a .length() method, so we created the above macro that allows you to specify the (size|length|count|whatever) method.

The obj->seq function can be used similar to the following example.
(let [positions (obj->seq position-collection size)]
; do stuff with positions
)
I'm fairly new to Clojure, so please feel free to provide recommendations and feedback.

From http://blog.jayfields.com/2010/04/clojure-converting-custom-collection-to.html

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}