Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Created June 7, 2015 20:55
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/f45d13f294cdeccada28 to your computer and use it in GitHub Desktop.
Save hhimanshu/f45d13f294cdeccada28 to your computer and use it in GitHub Desktop.
P05 (*) Reverse a list.
package com.learner.s99
/**
* P05 (*) Reverse a list.
* Example:
* scala> reverse(List(1, 1, 2, 3, 5, 8))
* res0: List[Int] = List(8, 5, 3, 2, 1, 1)
*/
object P05 {
def reverse[T](l:List[T]): Option[List[T]] = reverse(l, Nil)
private def reverse[T](l:List[T], reversed:List[T]): Option[List[T]] = {
l match {
case Nil => if (reversed.nonEmpty) Some(reversed) else None
case head::tail => reverse(tail, head::reversed)
}
}
}
package com.learner.s99
import com.learner.s99.P05.reverse
import org.scalatest.{MustMatchers, FlatSpec}
class P05Spec extends FlatSpec
with MustMatchers {
behavior of "A List"
it must "return Some(List(3,2,1)) for List(1,2,3) as reversed List" in {
reverse(List(1, 2, 3)) must be(Some(List(3, 2, 1)))
}
it must "return Some(List(1)) for List(1,2,3) as reversed List" in {
reverse(List(1)) must be(Some(List(1)))
}
it must "return None for empty list as reversed List" in {
reverse(List()) mustBe None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment