Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Last active August 29, 2015 14:22
Show Gist options
  • Save hhimanshu/746581d052e54c07aad5 to your computer and use it in GitHub Desktop.
Save hhimanshu/746581d052e54c07aad5 to your computer and use it in GitHub Desktop.
P01 (*) Find the last element of a list.
package com.learner.s99
/*
(*) Find the last element of a list.
Example:
scala> last(List(1, 1, 2, 3, 5, 8))
res0: Int = 8
*/
object P01 {
def last(input: List[Any]): Any = last(input, None)
private def last(input: List[Any], lastElement: Any): Any = input match {
case List() => lastElement
case head :: tail => last(tail, head)
}
}
package com.learner.s99
import com.learner.s99.P01.last
import org.scalatest.{FlatSpec, MustMatchers}
class P01Spec extends FlatSpec
with MustMatchers {
behavior of "A List"
it must "return 8 in List(1,2,3,4,5,6,7,8) as last element" in {
last(List(1, 2, 3, 4, 5, 6, 7, 8)) must equal(8)
}
it must "return 1 in List(1) as last element" in {
last(List(1)) must equal(1)
}
it must "return 'gamma' in List(alpha, beta, gamma) as last element" in {
last(List("alpha","beta", "gamma")) must equal("gamma")
}
it must "return 'two' in List(1, two) as last element" in {
last(List(1, "two")) must equal("two")
}
it must "return None empty List as last element" in {
last(List()) must be(None)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment