P03 - Find the nᵗʰ Element of a List
This problem is very nice because the Clojure and Scala implementations are practically the same. It allows to appreciate the different syntaxes better.
Below is Peter’s solution to the problem, in Clojure:
(defn kth [n xs]
{:doc "P03 (*) Find the Kth element of a list."
:pre [(seq? xs)]}
(if (= 0 n)
(first xs)
(recur (- n 1) (next xs)))
)
Here is my Scala:
def nth[T](n: Int, list: List[T]): T =
if (n == 0)
list.head
else
nth(n - 1, list.tail)
In this case one can see a small but significant difference where Clojure sticks to functional-programming and Scala favours object-oriented: while in Clojure first
and next
are functions that operate on collections, in Scala head
and tail
are methods to be called upon a collection instance.