我试着将出现在彼此旁边的项目分组,只要它们都在给定的“白名单”中分组必须至少包含两个或多个项。
例如,第一个参数是集合,第二个参数是白名单。

(group-sequential [1 2 3 4 5] [2 3])
>> ((2 3))

(group-sequential ["The" "quick" "brown" "healthy" "fox" "jumped" "over" "the" "fence"]
                  ["quick" "brown" "over" "fox" "jumped"])
>> (("quick" "brown") ("fox" "jumped" "over"))

(group-sequential [1 2 3 4 5 6 7] [2 3 6])
>> ((2 3))

这就是我想出来的:
(defn group-sequential
  [haystack needles]
  (loop [l haystack acc '()]
    (let [[curr more] (split-with #(some #{%} needles) l)]
      (if (< (count curr) 2)
        (if (empty? more) acc (recur (rest more) acc))
        (recur (rest more) (cons curr acc))))))

它能工作,但很难看。我想知道在clojure中是否有一种更简单的习惯用法?(你应该在我发现和…分手之前看到fn)
我敢打赌有一个很好的分隔线或什么的,但它晚了,我似乎无法使它工作。

最佳答案

(defn group-sequential [coll white]
  (->> coll
       (map (set white))
       (partition-by nil?)
       (filter (comp first next))))

是啊。更整洁的Diego Basch's method版本。

10-06 13:54