Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure pattern matching for vectors

I'd like to write a function that takes vectors [& x] and applies a test to pairs of elements. Outputting a vector of elements the test deemed identical and a vector of nil elements.

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]

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

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

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

If Input 2 is first flattened, it gives back Output 1.

like image 989
sunspots Avatar asked Nov 24 '25 13:11

sunspots


1 Answers

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]]]
like image 88
Arthur Ulfeldt Avatar answered Nov 26 '25 17:11

Arthur Ulfeldt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!