librelist archives

« back to archive

Epiphany

Epiphany

From:
Solomon White
Date:
2013-05-26 @ 22:33
I had an epiphany working through 4clojure #31 - pack a sequence.  The
general idea of the problem is to split a sequence into subsequences of the
same value, e.g.


'(1 1 1 2 2 3 1 1) => '((1 1 1) (2 2) (3) (1 1))


For my first attempt, I walked through how I would accomplish this, at a
fairly low level; the thought process was something like:  start with a
list containing an empty list, iterate through the given sequence, for each
value, if it matches the last thing in the last sublist, append it there,
otherwise append a new empty sublist and append the value into that.  I
ended up with this atrocity:


https://gist.github.com/rubysolo/5654257#file-pack1-clj


I knew there had to be a better way, so I thought more about *what* needed
to be done, instead of *how* to do it.  I want to split the sequence into
subsequences based on the value of consecutive items.  It finally became:


#(partition-by identity %1)