Example:
(deftest p02-penultimate (is (= 2 (penultimate (list 1 2 3)))))
Solution
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.
2 comments:
What does `recur` do in Clojure?
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
Post a Comment