Tuesday, February 04, 2014

99 Clojure Problems – 17: Split a List into Two Parts

The length of the first part is given. Use a tuple for your result.

Example:

(deftest p17-split
  (is (= ['(a b c) '(d e f g h i j k)]) (split 3 '(a b c d e f g h i j k))))

Solution:

There is a nice, functional, built-in solution in Clojure. I wanted to do it anyway.

My solution uses a nested, recursive function. Strictly speaking you cannot nest function definitions in Clojure in the same way as you can e.g. in Scala. But what you can do is to define a binding via let pointing to a function within another function. Since writing the solution I have learned that you can use letfn for this purpose.

The local function itself is fairly simple. It returns a vector (the tuple if you will) of the two lists and takes the length n of the first list, the list to break apart and the the initially empty result accumulator. We then "recur" by decrementing n, conjoining the first element to the result and passing on the rest of the sequence. When n becomes zero or we don't have anything left to split, we return the result.

Read more about this series.

No comments: