寻找分裂功能

时间:2017-01-25 23:02:42

标签: clojure

我正在寻找具有以下行为的功能

(split-on "" ("" "test" "one" "" "two"))
(() ("test" "one") ("two"))

我无法在“核心”中找到它,而且我不确定如何查找它。建议?

编辑: split-when看起来很有希望,但我认为我错了。

(t/split-when #(= "" %) '("" "test" "one" "" "two"))
[["" "test" "one" "" "two"] ()]

而我正在寻找的回报值     [[] [" test" "一个"] ["两个"]]

2 个答案:

答案 0 :(得分:4)

partition-by已接近尾声。您可以使用与拆分令牌相同的成员对序列进行分区:

(partition-by #(= "" %) '("" "test" "one" "" "two"))
(("") ("test" "one") ("") ("two"))

这会留下额外的分隔符,但这对remove来说很容易:

(remove #(= '("") %) 
       (partition-by empty? ["" "test" "one" "" "two"]))
(("test" "one") ("two"))

如果你想了解它并制作一个传感器,你可以这样定义一个:

(def split-on
  (comp
   (partition-by #(= "" %))
   (remove #(= '("") %))))

(into [] split-on ["" "test" "one" "" "two"])
[["test" "one"] ["two"]]

这是在没有建立中间结构的情况下“一次通过”。

将其转换为正常功能(如果您不需要换能器):

(defn split-on [coll]
  (into [] (comp
            (partition-by #(= "" %))
            (remove #(= '("") %)))
        coll))

答案 1 :(得分:4)

我最近正在寻找这个功能,不得不自己创建它。它可用in the Tupelo library。您可以在此处查看API文档:http://cloojure.github.io/doc/tupelo/tupelo.core.html#var-split-when

(split-when pred coll)
  Splits a collection based on a predicate with a collection 
  argument. Finds the first index N such that (pred (drop N coll)) 
  is true. Returns a length-2 vector of [ (take N coll) (drop N coll) ]. 
  If pred is never satisified, [ coll [] ] is returned.

单元测试显示功能在行动(无可否认无聊的测试数据):

(deftest t-split-when
  (is= [ [] [0   1   2   3   4]    ] (split-when #(= 0 (first %)) (range 5)))
  (is= [    [0] [1   2   3   4]    ] (split-when #(= 1 (first %)) (range 5)))
  (is= [    [0   1] [2   3   4]    ] (split-when #(= 2 (first %)) (range 5)))
  (is= [    [0   1   2] [3   4]    ] (split-when #(= 3 (first %)) (range 5)))
  (is= [    [0   1   2   3] [4]    ] (split-when #(= 4 (first %)) (range 5)))
  (is= [    [0   1   2   3   4] [] ] (split-when #(= 5 (first %)) (range 5)))
  (is= [    [0   1   2   3   4] [] ] (split-when #(= 9 (first %)) (range 5)))

如果您有兴趣,也可以read the source