In clojure why does splitting a string from an empty file return 1 element?
Consider the following:
=> (even? (count []))
true
so far so good. Now consider (assume my-file is empty):
(odd? (count (str/split (slurp my-file) #"\|")))
true
err ... why is the vector returned from an empty file not even (zero) ?
=>(str/split (slurp my-file) #"\|")
[""]
Ahh, can someone explain why an empty string is returned in this case?
I'm attempting t开发者_如何学Goo determine if there are an odd number of records in a file or not.
clojure.string/split
uses java.util.regex.Pattern/split
to do the splitting. See this question about Java for explanation. Namely, split
returns everything before the first match of your pattern as the first split, even if the pattern doesn't match at all.
The canonical way to test if a collection (list,array,map,string etc.) is empty or not is to call seq
on it, which will return nil
for an empty collection.
(defn odd-number-of-records? [filename]
(let [txt (slurp filename)]
(when (seq txt)
(odd? (count (str/split txt #"\|"))))))
精彩评论