简体   繁体   English

如何在Clojure中测试空向量

[英]How to test for an empty vector in Clojure

What's the best way to test for an empty vector in Clojure? 在Clojure中测试空向量的最佳方法是什么? I expected that this would print false: 我希望这会打印为false:

(if [] "true" "false")

but it doesn't. 但事实并非如此。 This does: 这样做:

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

but is unwieldy - is there a shorter construct? 但笨拙-是否有较短的结构?

使用标准谓词(empty? list)

The most common way I see in Clojure code to check for a non-empty list is to use seq . 我在Clojure代码中看到的最常见的检查非空列表的方法是使用seq This returns nil if the collection is empty, or a valid seq object otherwise. 如果集合为空,则返回nil,否则返回有效的seq对象。

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 (ie 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. 在clojure源代码中以(not (seq coll))因此您可以放心地知道这两种方法在本质上是等效的。

In addition to Mishadoff's answer (which is more readable), you could also compare against an empty list itself (and save two characters in length): 除了Mishadoff的答案(更具可读性)之外,您还可以将其与一个空列表进行比较(并保存两个字符的长度):

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

Hmmm... I still think I prefer Mishadoff's answer. 嗯...我还是觉得我更喜欢Mishadoff的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM