My Avatar

Shilong ZHAO

[s 99] p04 find the number of elements of a list

2020-06-22 00:00:00 +0200

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

Find the number of elements of a list.

Example:

scala> length(List(1, 1, 2, 3, 5, 8))
res0: Int = 6
def length[T](a: List[T]): Int = a.size
length(Nil)
length(List(1,2,3))
def lengthRecur[T](a: List[T]): Int = a match {
    case Nil => 0
    case _::xs => 1 + lengthRecur(xs)
}

lengthRecur(Nil)
lengthRecur(List(1,2,3,4))
def lengthWithFold[T](a: List[T]) = a.foldLeft(0)((l, _) => l + 1)

lengthWithFold(Nil)
lengthWithFold(List(1,2,3,4,5))