Alexey Orlov
Alexey Orlov

Reputation: 2804

Clojure: 'folding' a sequence (partitioning, as it turned out)

What is the right way of turning a flat list like this:

(1 2 3 4 5 6 7 8 9)

into a sequence of vectors:

([1 2 3] [4 5 6] [7 8 9])

Sorry, I suppose this is something right out of the toolbox, but I can't think of the right keyword.

Upvotes: 0

Views: 77

Answers (2)

adamjmarkham
adamjmarkham

Reputation: 2164

(->> '(1 2 3 4 5 6 7 8 9) (partition 3) (map vec)) 

Take the original list and then partition it by 3 and finally map each partition to a vector.

I think using the ->> macro makes it read nicer.

Upvotes: 4

runexec
runexec

Reputation: 862

user> (def flat-seq (range 1 10))
#'user/flat-seq
user> (map vec (partition-all 3 flat-seq))
;=> ([1 2 3] [4 5 6] [7 8 9])

Upvotes: 2

Related Questions