Created
June 7, 2015 04:40
-
-
Save hhimanshu/a064b984b8829daefaa6 to your computer and use it in GitHub Desktop.
P02 (*) Find the last but one 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 | |
/** | |
* (*) Find the last but one element of a list. | |
* Example: | |
* scala> penultimate(List(1, 1, 2, 3, 5, 8)) | |
* res0: Int = 5 | |
*/ | |
object P02 { | |
def penultimate(input: List[Any]): Any = penultimate(input, None, None) | |
private def penultimate(input: List[Any], secondLast: Any, last: Any): Any = input match { | |
case List() => secondLast | |
case head :: tail => penultimate(tail, last, head) | |
} | |
} |
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.P02.penultimate | |
import org.scalatest.{FlatSpec, MustMatchers} | |
class P02Spec extends FlatSpec | |
with MustMatchers { | |
behavior of "A List" | |
it must "return 7 in List(1,2,3,4,5,6,7,8) as penultimate element" in { | |
penultimate(List(1, 2, 3, 4, 5, 6, 7, 8)) must equal(7) | |
} | |
it must "return None in List(1) as penultimate element" in { | |
penultimate(List(1)) must be(None) | |
} | |
it must "return 'beta' in List(alpha, beta, gamma) as penultimate element" in { | |
penultimate(List("alpha","beta", "gamma")) must equal("beta") | |
} | |
it must "return 1 in List(1, two) as penultimate element" in { | |
penultimate(List(1, "two")) must equal(1) | |
} | |
it must "return None empty List as penultimate element" in { | |
penultimate(List()) must be(None) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment