Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created June 13, 2014 12:00
Show Gist options
  • Save MikeMKH/bef1093d69a6ac50bc29 to your computer and use it in GitHub Desktop.
Save MikeMKH/bef1093d69a6ac50bc29 to your computer and use it in GitHub Desktop.
FizzBuzz kata in Scala using Specs2
name := "Fizz Buzz"
version := "1.0"
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
"org.specs2" %% "specs2" % "2.3.12" % "test"
)
scalacOptions in Test ++= Seq("-Yrangepos")
resolvers ++= Seq("snapshots", "releases").map(Resolver.sonatypeRepo)
package com.kata.spec2
import org.specs2._
import matcher.DataTables
object FizzBuzzer {
class FizzBuzzExtractor[T](f: T => Boolean) {
def unapply(x: T) = f(x)
}
val FizzBuzz = new FizzBuzzExtractor[Int](_ % 15 == 0)
val Fizz = new FizzBuzzExtractor[Int](_ % 3 == 0)
val Buzz = new FizzBuzzExtractor[Int](_ % 5 == 0)
def eval(value: Int) = value match {
case FizzBuzz() => "FizzBuzz"
case Fizz() => "Fizz"
case Buzz() => "Buzz"
case _ => value.toString
}
}
class FizzBuzzSpec extends Specification with DataTables { def is = s2"""
the following truth $table gives inputs and expected results for FizzBuzz
"""
def table =
"input" | "result" |>
2 ! "2" |
3 ! "Fizz" |
5 ! "Buzz" |
15 ! "FizzBuzz" |
33 ! "Fizz" |
55 ! "Buzz" |
150 ! "FizzBuzz" |
151 ! "151" | { (a, b) => { FizzBuzzer.eval(a) must_== b } }
}
@MikeMKH
Copy link
Author

MikeMKH commented Jun 21, 2014

See also my blog post which goes with this gist: http://comp-phil.blogspot.com/2014/06/specs-in-scala-and-c.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment