目次
Scalaで型レベルfizzbuzz
Kazuki Moriyama (森山 和樹)
昔作ったやつのメモ。
Scala2でshapelessを使ってる。
import shapeless.Nat
import shapeless.nat._
import shapeless.ops.nat._
trait FizzBuzz[N <: Nat] {
def apply(): String
}
object FizzBuzz extends FizzBuzzLowerPriorityImplicits {
def apply[N <: Nat](implicit lt: LT[_0, N], fizzbuzz: FizzBuzz[N]): String = fizzbuzz()
implicit def fizzbuzz[N <: Nat](implicit mod: Mod.Aux[N, _15, _0]): FizzBuzz[N] =
new FizzBuzz[N] {
def apply(): String = "FizzBuzz"
}
}
trait FizzBuzzLowestPriorityImplicits {
implicit def number[N <: Nat](implicit toInt: ToInt[N]): FizzBuzz[N] =
new FizzBuzz[N] {
def apply(): String = toInt().toString
}
}
trait FizzBuzzLowerPriorityImplicits extends FizzBuzzLowestPriorityImplicits {
implicit def fizz[N <: Nat](implicit mod: Mod.Aux[N, _3, _0]): FizzBuzz[N] =
new FizzBuzz[N] {
def apply(): String = "Fizz"
}
implicit def buzz[N <: Nat](implicit mod: Mod.Aux[N, _5, _0]): FizzBuzz[N] =
new FizzBuzz[N] {
def apply(): String = "Buzz"
}
}
FizzBuzz[_2] // => "2"
FizzBuzz[_3] // => "Fizz"
FizzBuzz[_5] // => "Buzz"
FizzBuzz[_6] // => "Fizz"
FizzBuzz[_15] // => "FizzBuzz"