From b9c3b0272554753a3622d37835fb57588e47714c Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Mon, 14 Feb 2011 15:31:49 -0800 Subject: [PATCH] Added some sequence exercises. --- src/main/scala/example/Sequences.scala | 22 ++++++++++++++++++++++ src/main/scala/example/package.scala | 5 ++++- src/test/scala/ExampleSpec.scala | 8 +++++++- 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 src/main/scala/example/Sequences.scala diff --git a/src/main/scala/example/Sequences.scala b/src/main/scala/example/Sequences.scala new file mode 100644 index 000000000..be25b0e31 --- /dev/null +++ b/src/main/scala/example/Sequences.scala @@ -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) + } +} \ No newline at end of file diff --git a/src/main/scala/example/package.scala b/src/main/scala/example/package.scala index 09ad32615..5581bcb09 100644 --- a/src/main/scala/example/package.scala +++ b/src/main/scala/example/package.scala @@ -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.") } \ No newline at end of file diff --git a/src/test/scala/ExampleSpec.scala b/src/test/scala/ExampleSpec.scala index 01ad8a1f1..2b2ee3d61 100644 --- a/src/test/scala/ExampleSpec.scala +++ b/src/test/scala/ExampleSpec.scala @@ -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) + } } }