Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to determine if there are an odd number of records in a file or not.

like image 978
SMTF Avatar asked Jun 21 '11 21:06

SMTF


People also ask

What happens if you split an empty string?

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.

Does Split always return a list?

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.


1 Answers

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 #"\|"))))))
like image 110
Brian Carper Avatar answered Nov 15 '22 08:11

Brian Carper