Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How roughen (as opposed to flatten) a list in a functional style?

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.

like image 413
user342304 Avatar asked May 20 '10 15:05

user342304


2 Answers

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))
like image 113
Thomas Jung Avatar answered Nov 15 '22 10:11

Thomas Jung


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.

like image 21
Michał Marczyk Avatar answered Nov 15 '22 11:11

Michał Marczyk