我试图将直接出现在彼此旁边的项目分组,只要它们都在给定的“白名单”中即可。分组必须至少包含两个或更多项目。
例如,第一个参数是集合,第二个参数是白名单。
(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 中是否有更简单的惯用方法? (在我发现 split-with 之前你应该已经看到了 fn :)
我打赌有一个很好的单行代码,带有分区或其他东西,但已经晚了,我似乎无法让它工作。
最佳答案
(defn group-sequential [coll white]
(->> coll
(map (set white))
(partition-by nil?)
(filter (comp first next))))
... Diego Basch's method 的更简洁版本。
关于algorithm - Clojure 组顺序出现 - 改进功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26352385/