Friday, August 26, 2011

Programming Praxis: Reverse sublists

Today's problem should be especially easy in clojure given clojure's partition functions. Let's see if I'm right.

First we create a linked list using the native java class java.util.LinkedList. What's really neat here is that clojure's sequence functions all work on java's native collection classes. So the solution is super easy at that point. Partition the list into k elements and then mapcat that list using reverse.

;;Reverse k nodes

(def linked-list (java.util.LinkedList. [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]))

(defn reverse-sub-lists [l k]
  (mapcat reverse (partition-all k l)))

The more I use clojure the more I like it!


No comments:

Post a Comment