user4813927
user4813927

Reputation:

The use of Seq function in Clojure

From the manual of clojure about seq we read: ;; (seq x) is the recommended idiom for testing if a collection is not empty (every? seq ["1" [1] '(1) {:1 1} #{1}]) ;;=> true. But an empty collection returns itself also nil, so what the point of this usage of seq for testing emptiness of a collection?

Upvotes: 2

Views: 139

Answers (2)

Diego Basch
Diego Basch

Reputation: 13059

An empty collection is not falsey, so in a test it won't matter if it's empty or not:

(if '() "a" "b")
=> "a"

So if you want to do something else if it's empty:

(if (seq '()) "a" "b")
=> "b"

Upvotes: 3

leeor
leeor

Reputation: 17771

From the docs at the top of that page:

seq also works on Strings, native Java arrays (of reference types) and any objects that implement Iterable

So using seq to test emptiness works across any of these collection types. So you get a consistent idiomatic way to check emptiness on any of these types as the example demonstrates.

The fact that seq returns nil on both an empty collection and on nil makes the check simpler as well, as opposed to needing to check for empty or nil.

Upvotes: 3

Related Questions