Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for an empty vector in Clojure

Tags:

clojure

What's the best way to test for an empty vector in Clojure? I expected that this would print false:

(if [] "true" "false")

but it doesn't. This does:

(if (> (count []) 0) "true" "false")

but is unwieldy - is there a shorter construct?

like image 390
Kevin Burke Avatar asked Nov 21 '11 22:11

Kevin Burke


People also ask

How do you check if a string is empty in Clojure?

Idiom #110 Check if string is blank. Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise. (require '[clojure. string :refer [blank?]])

What is a vector in Clojure?

A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.


1 Answers

The most common way I see in Clojure code to check for a non-empty list is to use seq. This returns nil if the collection is empty, or a valid seq object otherwise.

Example of usage:

(seq [])
=> nil

(seq nil)
=> nil

(seq [1 2 3])
=> (1 2 3)         ;; note this is a "true value"

(if (seq [1 4 6]) "true" "false")
=> "true"

(if (seq []) "true" "false")
=> "false"

You can also use empty? to test the opposite (i.e. test for an empty set). Note that empty? is implemented in the clojure source code as (not (seq coll)) so you can be safe in the knowledge that the two approaches are fundamentally equivalent.

like image 139
mikera Avatar answered Sep 16 '22 11:09

mikera