Created
June 7, 2015 05:18
-
-
Save hhimanshu/0acccf2d5f392024e65d to your computer and use it in GitHub Desktop.
P03 (*) Find the Kth element 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 | |
object P03 { | |
def nth(n: Int, l: List[Any]): Any = { | |
require(n >= 0, "n must be greater than or equal to zero") | |
l match { | |
case List() => None | |
case head :: tail if n == 0 => head | |
case head :: tail if n > 0 => nth(n - 1, tail) | |
} | |
} | |
} |
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 com.learner.s99.P03._ | |
import org.scalatest.{MustMatchers, FlatSpec} | |
class P03Spec extends FlatSpec | |
with MustMatchers { | |
behavior of "A List" | |
it must "return 0 in List(0,1,2,3) as 0th element" in { | |
nth(0, List(0, 1, 2, 3)) mustBe 0 | |
} | |
it must "return 3 in List(0,1,2,3) as 3rd element" in { | |
nth(3, List(0, 1, 2, 3)) mustBe 3 | |
} | |
it must "return None in List(0,1,2,3) as 10th element" in { | |
nth(10, List(0, 1, 2, 3)) mustBe None | |
} | |
it must "throw an IllegalArgumentException for negative index in list" in { | |
an [IllegalArgumentException] must be thrownBy nth(-10, List(0, 1, 2, 3)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment