P05 - Reverse a List

Clojure – recursive:

(defn my-reverse [xs]
  "P05 (*) Reverse a list"
  (loop [ret [] xs xs]
    (if (empty? xs)
      ret
      (recur (cons (first xs) ret) (next xs)))))

Clojure – with reduce:

(defn my-reverse-reduce [xs]
  "P05 (*) Reverse a list"
  (reduce #(cons %2 %1) '() xs))

Scala – recursive:

def reverse[T](list: List[T]): List[T] = {
  def helper(remaining: List[T], reversed: List[T]): List[T] =
    remaining match {
      case Nil => reversed
      case first :: rest => helper(rest, first :: reversed)
    }
  helper(list, Nil)
}

Scala – with folding:

def reverseFolding[T](list: List[T]): List[T] =
  list.foldLeft(List.empty[T])((result, element) => element :: result)