Skip to main content

99 Scala Problems Challenge – 4/333

Problem 4 – Find the number of elements of a list

P04 (*) Find the number of elements of a list.
Example:
scala> length(List(1, 1, 2, 3, 5, 8))
res0: Int = 6

I’ve started with writing some tests to verify my future implementation


test("that empty list is of length 0") {
    p04.length(List()) should equal(0)
  }

test("that one-element list is of length 1") {
    p04.length(List(1)) should equal(1)
}

test("that returns the list length") {
    p04.length(List(1, 3, 7, 9, 0)) should equal(5)
}}

I was astonished when realized how practice makes eventually everything natural. I could almost see the implementation in front of my eyes, before I wrote any code. Pattern matching & tail recursion were manifesting them selves as if it was no longer any other way to solve this problem.


class P04[T] {
  final def length(list: List[T]): Int = {
    @tailrec
    def sum(acc: Int, lt: List[T]): Int = lt match {
      case Nil => acc
      case head :: tail => sum(acc + 1, tail)
    }
    sum(0, list)
  }
}

Reference implementation was 100% identical to the one I wrote, however they’ve also proposed more pure functional solution (using folds) which I’ve also enjoyed

def lengthFunctional[A](ls: List[A]): Int = 
     ls.foldLeft(0) { (c, _) => c + 1 }

 

 

Source code for this blog post is available at Github.