Skip to content

Programming · Games · Life outdoors

Checking for Empty Seqs in Clojure

When coming from other languages, devs often think the best way to check for an empty vector or other sequence in Clojure is to either check the count  is less than one or check for (not (empty? some-seq)) . Both will work, but are not idiomatic, meaning “Your newbness is showing.”

The idiomatic way to check for empty sequences in Clojure is to use seq . seq  returns nil  (falsy value) when a sequence is empty. Here’s an example.

(ns example.core)
(defn -main
[& args]
(def some-vec [])
(def some-other-vec [42])
(if (seq some-vec)
(println "some-vec is has some value")
(println "some-vec is empty"))
(if (seq some-other-vec)
(println "some-other-vec is has some value")
(println "some-other-vec is empty")))

The result of this code running will be as follows.

some-vec is empty
some-other-vec is has some value

Remember, strings are sequences, so (seq "")  will also be falsy.

The moral of the story is use seq to check for empty sequences in Clojure! If you want to see a specific Clojure tutorial, please let me know on Twitter.