Saturday, January 11, 2014

99 Clojure Problems – 2: Find the Penultimate Element of a List

Example:

(deftest p02-penultimate
  (is (= 2 (penultimate (list 1 2 3)))))

Solution

Source

There are multiple ways of solving this problem. I used a variation of the solution to the first problem. Instead of recurring on the function itself, I added an additional loop form, which allowed me to keep track of the first element in each of the sublists. Once the evaluation reaches the sublist of the last two elements, the first element of this list is also the element we are looking for.

I also added a precondition to the function to ensure the parameter is a Sequence.

Read more about this series.

2 comments:

Sebastian said...

What does `recur` do in Clojure?

Peter Brachwitz said...

It's working around the fact that there is no proper tail-call optimisation on the JVM. It basically allows stack-neutral self-recursion to the surrounding loop form or the function itself: http://clojure.org/special_forms#recur