25

What is the difference between the functions seq? sequential? and coll?

I found some information scattered throughout the internet, but I think it would be better to centralize that information here.

Carlos Nunes
  • 1,929
  • 2
  • 16
  • 20

2 Answers2

29

seq? is a predicate that returns true if it's argument implements ISeq interface, which is to say it provides the methods first,rest,cons. See http://clojure.org/sequences.

(seq? [1 2])
false
(seq? (seq [1 2]))
true

sequential? is a predicate that returns true if it's argument implements Sequential interface. Sequential is a marker interface (no methods) and is a promise that the collection can be iterated over in a defined order (e.g. a list, but not a map).

(sequential? [])
true
(sequential? {})
false

coll? is a predicate that returns true if its argument implments IPersistentCollection. So for example the clojure data structures would return true, whereas native java data structures would not:

(coll? {:a 1})
true
(coll? (java.util.HashMap.))
false
Kevin
  • 24,871
  • 19
  • 102
  • 158
  • 4
    Vectors provide `first`, `rest`, and `cons`, yet they aren't `seq?`? – FeifanZ Feb 19 '16 at 20:23
  • 4
    @FeifanZ, these(`first`,`rest`,`cons`) functions first call [seq](http://clojuredocs.org/clojure.core/seq) function for its argument. So if you use these functions for vector (`clojure.lang.PersistentVector`) which doesn't implement ISeq interface (seq? function return `false`), it means that you use these function for vector (`clojure.lang.PersistentVector$ChunkedSeq`) which implements ISeq interface(seq? return `true`). – snufkon Apr 01 '16 at 23:46
9
  • seq? is true for any sequence.
  • sequential? is true for any sequential (not associative) collection.
  • coll? is true for any Clojure collection.

seq? implies sequential? implies coll?

=> ((juxt seq? sequential? coll?) ()) ; [true true true]
=> ((juxt seq? sequential? coll?) []) ; [false true true]
=> ((juxt seq? sequential? coll?) #{}); [false false true]

Inaccurate: sequential? is related to the others purely by convention - see Kevin's answer.

Community
  • 1
  • 1
Thumbnail
  • 13,293
  • 2
  • 29
  • 37