Created
June 7, 2015 05:36
-
-
Save hhimanshu/370bf40cfd24a3fb8c75 to your computer and use it in GitHub Desktop.
P04 (*) Find the number of elements of a list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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