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?
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?]])
A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With