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 to determine if there are an odd number of records in a file or not.
The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.
However, if an argument is given, it is treated as a single delimiter with no repeated runs. In the case of splitting an empty string, the first mode (no argument) will return an empty list because the whitespace is eaten and there are no values to put in the result list.
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 #"\|"))))))
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