Sunday, January 12, 2014

99 Clojure Problems – 3: Find the Kth Element of a List

Example:

(deftest p03-kth
  (is (= 3 (kth 2 (list 1 2 3 4)))))

Solution

There is a built-in function called nth that solves this problem.

Source

A relatively straightforward recursive solution uses recur on the function itself while decrementing the k and dropping the first element on each recursive call until we reach k = 0 at which point we return the first element. Strictly speaking this is a linear iterative process and not a recursive one as all the state of the process is in its parameter bindings and not in the results of the stack of recursive calls.

Read more about this series.

No comments: