简体   繁体   English

在Clojure中使用Seq函数

[英]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 clojure关于seq手册中,我们读到: ;; (seq x) is the recommended idiom for testing if a collection is not empty (every? seq ["1" [1] '(1) {:1 1} #{1}]) ;;=> true ;; (seq x) is the recommended idiom for testing if a collection is not empty (every? seq ["1" [1] '(1) {:1 1} #{1}]) ;;=> true . ;; (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? 但是空集合本身也返回nil ,那么使用seq测试集合的空性有什么意义呢?

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 seq还可用于字符串,本机Java数组(引用类型)和任何实现Iterable的对象

So using seq to test emptiness works across any of these collection types. 因此,使用seq测试空度适用于所有这些收集类型。 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. 如SEQ回报的事实nil两个空的收集和nil ,使检查更简单为好,而不是需要检查空或零。

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"

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

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