For instance, I have a list (1 2 3 4 5 6 7 8 9 10 11)
, and want to roughen it by 3 elements (or another length) to get ((1 2 3) (4 5 6) (7 8 9) (10 11))
. What pretty code could I use for this? Thanks.
List(1,2,3,4,5,6,7,8,9,10,11) grouped 3 toList
res0: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6),
List(7, 8, 9), List(10, 11))
Since you use the Clojure tag too...
There's a built-in function to do that in Clojure 1.2, also available in 1.1 in clojure.contrib.seq-utils.
(partition-all 3 [1 2 3 4 5 6 7 8 9 10 11])
; => ((1 2 3) (4 5 6) (7 8 9) (10 11))
See also partition
and partition-by
. Also note that partition
and partition-all
accept some optional arguments if you need something slightly different, see e.g. (doc partition)
at the REPL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With