Why prefer seq over non-empty as a predicate?
中使用
1 2 3 | (if-let [s (seq might-be-empty)] (fn-for-non-empty-seq s) (fn-for-empty-seq)) |
我是否应该真的使用
1 2 3 4 5 6 7 8 | user=> (class (lazy-seq '(1 2 3))) clojure.lang.LazySeq user=> (class (seq (lazy-seq '(1 2 3)))) clojure.lang.PersistentList user=> (class (map inc [1 2 3])) clojure.lang.LazySeq user=> (class (seq (map inc [1 2 3]))) clojure.lang.ChunkedCons |
如果只是想测试非空性,不需要新的绑定,或者如果我不需要在绑定之前进行转换,那似乎是周期的浪费。在这种情况下
1 2 3 | (if (not-empty []) "more to do" "all done") |
首先,检查
1 2 3 4 5 6 | (defn empty? "Returns true if coll has no items - same as (not (seq coll)). Please use the idiom (seq x) rather than (not (empty? x))" {:added"1.0" :static true} [coll] (not (seq coll))) |
所以
现在请参阅
1 2 3 4 5 | (defn not-empty "If coll is empty, returns nil, else coll" {:added"1.0" :static true} [coll] (when (seq coll) coll)) |
惊奇,它也使用
请不要担心