Clojure:连续重复项的数量

pis*_*hio 2 clojure

我需要一个函数来计算序列中连续相等条目的数量.例如,(连续的"abcdefg")应该返回0,而(连续的"aabcdddefg")应该返回3.

我写的方式是惯用还是可以改进?

(defn consecutive [p]
  (second (reduce
            #(vector %2
                     (if (= (first %1) %2)
                       (inc (second %1))
                       (second %1)))
            [nil 0]
            p)))
Run Code Online (Sandbox Code Playgroud)

mik*_*era 5

我认为(consecutive "abcdefg")应该返回1,而不是0.

这是一个实现此目的的简单实现:

(defn consecutive [s] 
  (apply max (map count (partition-by identity s))))
Run Code Online (Sandbox Code Playgroud)