Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unflattening a sequence to sequences of repeating elements (clojure)

Tags:

clojure

In Clojure, how do you partition a sequence to subsequences of repeating elements? E.g. :

[1 2 2 3 3 3 4 2 2 1 1 1]

to

[[1] [2 2] [3 3 3] [4] [2 2] [1 1 1]]

I've been playing around with some examples trying to understand clojure better, and was stuck on this one for some time.

like image 826
aeter Avatar asked Dec 06 '10 19:12

aeter


2 Answers

user> (partition-by identity [1 2 2 3 3 3 4 2 2 1 1 1])
((1) (2 2) (3 3 3) (4) (2 2) (1 1 1))

user> (vec (map vec (partition-by identity [1 2 2 3 3 3 4 2 2 1 1 1])))
[[1] [2 2] [3 3 3] [4] [2 2] [1 1 1]]
like image 112
Brian Carper Avatar answered Nov 16 '22 07:11

Brian Carper


(map (juxt count first) (partition-by identity [1 1 1 3 2 2]))

((3 1) (1 3) (2 2))

Three ones, then one three, followed by two twos!

like image 2
amalloy Avatar answered Nov 16 '22 07:11

amalloy