Friday, January 10, 2014

99 Clojure Problems – 1: Find the Last Element of a List

Example:

(deftest p01-last
    (is (= 3 (last (list 1 2 3)))))

Solution:

There is a built-in function that does just that.

Source.

If you don't want to use the built-in, one possible approach with linear time complexity is to check if there is a next element in the list after the head. If there is one, use the special form recur to recursively apply the function again to the tail of the list until there is no "next" element. Then return the first element, which is also the last. Using "recur" has the added benefit of being non-stack-consuming.

Read more about this series.

No comments: