Pure Danger Tech


Learning Clojure #14: partition

29 Apr 2010

I ran into a case today where I had a sequence that had pairs of items I wanted to process. Imagine something like (:a 1 :b 2 :c 3) and I want to evaluate a function on (:a 1), then (:b 2) etc.

I’ve run into this a couple times now and found other ways to massage the inputs or the processing. But it struck me today that there has to be a function to lazily restructure the stream to chunk up parts of it. And in fact with a quick search by my colleagues, there is: partition.

Partition lets you do exactly this taking n items at a time and also lets you choose a step function to even overlap the partitions. Here’s a few examples to get the idea:

user=> (partition 2 [:a 1 :b 2 :c 3])<br /> ((:a 1) (:b 2) (:c 3))<br /> user=> (partition 4 [:a 1 :b 2 :c 3 :d 4])<br /> ((:a 1 :b 2) (:c 3 :d 4))<br /> user=> (partition 2 1 [:a 1 :b 2 :c 3])<br /> ((:a 1) (1 :b) (:b 2) (2 :c) (:c 3))

The last example uses a step of 1; by default if not specified the step is the same size as the partition. Really the first and last examples here are cases that are exceedingly useful for dealing with a lot of common data structure cases.