Created
June 7, 2015 20:55
-
-
Save hhimanshu/f45d13f294cdeccada28 to your computer and use it in GitHub Desktop.
P05 (*) Reverse 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 | |
/** | |
* 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) | |
} | |
} | |
} |
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.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