Saturday, January 11, 2014

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


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



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.


Sebastian said...

What does `recur` do in Clojure?

pbrc 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: