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.
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.
No comments:
Post a Comment