P04 - Find the Number of Elements of a List
Clojure recursive:
(defn my-count [xs]
"P04 (*) Find the number of elements of a list."
(loop [num 0 xs xs]
(if (next xs)
(recur (+ num 1) (next xs))
(+ num 1))))
Clojure with reduce:
(defn my-count-reduce [xs]
"P04 (*) Find the number of elements of a list."
(reduce (fn [[c xs]] (inc c)) 0 xs))
Scala recursive:
def length[T](list: List[T]): Int =
list match {
case Nil => 0
case x :: rest => 1 + length(rest)
}
Scala foldLeft:
def length[T](list: List[T]): Int =
list.foldLeft(0)((count, _) => 1 + count)
This last can probably be improved.