Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Created June 7, 2015 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hhimanshu/370bf40cfd24a3fb8c75 to your computer and use it in GitHub Desktop.
Save hhimanshu/370bf40cfd24a3fb8c75 to your computer and use it in GitHub Desktop.
P04 (*) Find the number of elements of a list.
package com.learner.s99
/**
* (*) Find the number of elements of a list.
* Example:
* scala> length(List(1, 1, 2, 3, 5, 8))
* res0: Int = 6
*/
object P04 {
def length(l: List[Any]): Int = length(l, 0)
private def length(l: List[Any], lengthSoFar: Int): Int = l match {
case List() => lengthSoFar
case head::tail => length(tail, lengthSoFar + 1)
}
}
package com.learner.s99
import org.scalatest.{MustMatchers, FlatSpec}
class P04Spec extends FlatSpec
with MustMatchers {
behavior of "A List"
it must "return 4 for List(1,2,3,4) as length" in {
P04.length(List(1,2,3,4)) mustBe 4
}
it must "return 0 empty List as length" in {
P04.length(List()) mustBe 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment