mike-neckのブログ

Java or Groovy or Swift or Golang

なんかJavaの人たちでじゃんけんのプログラムが流行ってるので、便乗して書いてみた Scala編

昨日便乗して書いたのはGroovyで今日書いてみたのはScalaの場合のじゃんけん。

まともにScalaのプログラムを書いたのは実はこれがはじめて…

trait Result {
  def で(expected: Result):Unit = {
    val self = this
    assert(self == expected)
  }
}
object Result {
  case object 勝ち extends Result
  case object あいこ extends Result
  case object 負け extends Result
}

trait じゃんけん {
  def 相手(other: じゃんけん): Result = {
    val self = this
    other match {
      case `next` => Result.勝ち
      case `self` => Result.あいこ
      case _ => Result.負け
    }
  }
  protected val next: じゃんけん
}

object じゃんけん {
  case object グー extends じゃんけん {protected val next = チョキ}
  case object チョキ extends じゃんけん {protected val next = パー}
  case object パー extends じゃんけん {protected val next = グー}
}


object RockPaperScissor extends App {
  import じゃんけん._
  import Result._

  じゃんけん.グー 相手 チョキ で 勝ち
  じゃんけん.グー 相手 グー で あいこ
  じゃんけん.グー 相手 パー で 負け

  じゃんけん.チョキ 相手 チョキ で あいこ
  じゃんけん.チョキ 相手 グー で 負け
  じゃんけん.チョキ 相手 パー で 勝ち

  じゃんけん.パー 相手 チョキ で 負け
  じゃんけん.パー 相手 グー で 勝ち
  じゃんけん.パー 相手 パー で あいこ
}

あとはscalac RockPaperScissor.scalaからscala RockPaperScissorとやれば、実行される