Added some sequence exercises.

This commit is contained in:
Paul Phillips 2011-02-14 15:31:49 -08:00
parent fa1f988bcf
commit b9c3b02725
3 changed files with 33 additions and 2 deletions

View File

@ -0,0 +1,22 @@
package example
// These implementations have no error checking: they will throw
// exceptions if the input is unexpected, e.g. an empty list has no
// penultimate member.
object Exercises {
def penultimate[T](xs: List[T]): T = xs.reverse.tail.head
// Other possible implementations:
// def penultimate[T](xs: List[T]): T = xs.init.last
// def penultimate[T](xs: List[T]): T = xs(xs.length - 2)
// def penultimate[T](xs: List[T]): T = xs takeRight 2 head
// Test if the argument is a palindrome.
def isPalindrome[T](xs: List[T]) = xs == xs.reverse
// Remove the Kth element from a list, returning the list and
// the removed element as a tuple.
def removeAt[T](index: Int, xs: List[T]): (List[T], T) = {
val (front, back) = xs splitAt index
(front ++ back.tail, back.head)
}
}

View File

@ -2,5 +2,8 @@
package object example {
// Importing an implicit method of type Int => Rational will
// henceforth let us use Ints as if they were Rationals.
implicit def intToRational(num: Int): Rational = new Rational(num)
implicit def intToRational(num: Int): Rational = new Rational(num)
// A handy method for exercises yet to be performed.
def ?? = throw new RuntimeException("Unimplemented.")
}

View File

@ -4,10 +4,16 @@ import org.specs._
class ExampleSpec extends Specification {
"An example project" should {
"implement rational numbers" >> {
"compare Rationals" >> {
Rational(5) mustEqual Rational(5, 1)
Rational(1, 10) mustEqual Rational(2, 20)
}
"add Rationals" >> {
(Rational(1, 3) + Rational(5, 15)) mustEqual Rational(4, 6)
}
"mix and match Rationals and Ints" >> {
(Rational(1, 2) + 1) mustEqual Rational(3, 2)
(1 + Rational(1, 2)) mustEqual Rational(3, 2)
}
}
}