Newcomers to Clojure are often confused by the collection and sequence abstractions and how they relate to one another. This document aims to provide an overview of these concepts and how they may be used in one's code.
seq
.seq
in user code
is to check if a collection or collection-like will yield elements.
Clojure's Collection API provides a generic mechanism for creating and handling
compound data.
Technically, a Clojure collection is an object claiming the
clojure.lang.IPersistentCollection
interface.
This may be discovered using the predicate coll?
.
The associated conceptual abstraction is that of a bag o' values,
supporting certain operations:
Adding, removing, counting, finding, and iterating over the values.
Commonly seen examples are lists, maps, vectors, sets, and seqs,
but these are not the only collection types that Clojure provides.
Different collection types have different APIs, performance characteristics, and intended patterns of usage. Any given collection may match one or more of the following predicates, which group collection types by their broad characteristics:
counted?
count
in constant time, without actually traversing their data.
This is not just a performance characteristic —
some collections are infinite or may not be able to predict their size
without running arbitrary code.associative?
sequential?
Here we see which collections support which predicates, as well as how some non-collections are treated:
'(1 2 3) | [4 5 6] | {:a 1, :b 2} | #{7 8 9} | "hello" | nil | (range) | (seq "hello") |
|
---|---|---|---|---|---|---|---|---|
coll? |
||||||||
counted? |
||||||||
sequential? |
||||||||
associative? |
Note that the string is not a collection, but may be converted into one.
TODO: Raid clojure.core repo for instances of IPersistentCollection, ISeq, etc.
A sequence is a data structure that is expected to be accessed in a sequential manner. It may be infinitely long, and may require additional computation in order to read.
TODO: seq API
Nota Bene: Sequences are not implemented as lists, they just act a lot like them and may be backed by similar data structures.
TODO: counted?
TODO: Equality partitions re: seqs and colls
() | [] | {} | #{} |
|
---|---|---|---|---|
#(= () %) |
||||
#(= [] %) |
||||
#(= {} %) |
||||
#(= #{} %) |
TODO: effect of metadata, sortedness
TODO: comparison with other Java Collections