Tuesday, January 14, 2014

99 Clojure Problems – 5: Reverse a List

Example:

(deftest p05-reverse
  (is (= '(3 2 1) (my-reverse '(1 2 3)))))

Solution:

Now this might be a bit disappointing but my two solutions to this problem are structurally very similar to the solutions to problem no. 4. One way of reversing a list is to recursively call reverse with the tail of the list until all that is left is an empty list. We cons the head of the current list to the result on the way and return the reversed result when we hit the base case.

Another solution could use reduce to cons the elements together in a similar fashion. The val parameter initialised with an empty list is used again as an accumulator to build up the result.

Finally there is, of course, also the built-in reverse.

Read more about this series.

No comments: