简体   繁体   English

矢量的Clojure模式匹配

[英]Clojure pattern matching for vectors

I'd like to write a function that takes vectors [& x] and applies a test to pairs of elements. 我想编写一个函数,它接受向量[&x]并将测试应用于元素对。 Outputting a vector of elements the test deemed identical and a vector of nil elements. 输出测试认为相同的元素向量和nil元素的向量。

My first thought is to take the vectors and flatten them. 我的第一个想法是采用向量并展平它们。

(defn soup [& x]
    (vec (flatten x))

Then apply a test such as identical? 然后应用相同的测试? neg? 负? or something along those lines. 或类似的规定。 It's at the point of pattern matching that I am stuck in trying to assemble the output. 正是在模式匹配方面,我一直试图组装输出。

Ex) Input 1: [:a :b :c :a :b :c] 例)输入1:[:a:b:c:a:b:c]

Output 1: [[:a :a] [:b :b] [:c :c]] 输出1:[[:a:a] [:b:b] [:c:c]]

Input 2: [[:a :b :c] [:a :b :c]] 输入2:[[:a:b:c] [:a:b:c]]

Output 2: [[[:a :b :c] [:a :b :c]]] 输出2:[[[:a:b:c] [:a:b:c]]]

If Input 2 is first flattened, it gives back Output 1. 如果输入2首先变平,则返回输出1。

Would combining sort and partition-by be close to what you are asking for? 结合排序和分区是否接近你所要求的?

(->> [:a :b :c :a :b :c] sort (partition-by identity))
((:a :a) (:b :b) (:c :c)) 

(->> [[:a :b :c] [:a :b :c]] sort (partition-by identity))
(([:a :b :c] [:a :b :c]))

and if you need them to be vectors after: 如果你需要它们之后是矢量:

(->> [:a :b :c :a :b :c] sort (partition-by identity) (map vec) vec)
[[:a :a] [:b :b] [:c :c]]

(->> [[:a :b :c] [:a :b :c]] sort (partition-by identity) (map vec) vec)
[[[:a :b :c] [:a :b :c]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM