Upgrade to Pro — share decks privately, control downloads, hide ads and more …

見せ算をScalaで実装してみた / Scalaわいわい勉強会 #2

Arthur
February 27, 2024

見せ算をScalaで実装してみた / Scalaわいわい勉強会 #2

さや香の見せ算 (https://www.youtube.com/watch?v=QSfNwVBg3EA) をScalaで実装しましたという小話です

https://scala-tokyo.connpass.com/event/297260/

Arthur

February 27, 2024
Tweet

More Decks by Arthur

Other Decks in Programming

Transcript

  1. 演算子はメソッド 16 case class MyInt (v: Int) { def unary_-

    : MyInt = MyInt(-this.v) def +(that: MyInt): MyInt = MyInt(this.v + that.v) } -MyInt(4) // MyInt(-4) MyInt(3) + MyInt(2) // MyInt(5) https://scastie.scala-lang.org/N10goNFbQj6eOwmPzGPDRQ
  2. 既存の型の拡張ができる 17 implicit class ExtendedInt(val i: Int) { def **(j:

    Int): Int = if (j <= 0) 1 else i ** (j - 1) * i } 3 ** 2 // 9 ビルトインの型にも演算子を増やせる https://scastie.scala-lang.org/CvFRoSDPQF6gWilg9hHCKQ
  3. Scala 3 からは…… 18 extension (i: Int) def **(j: Int):

    Int = if (j <= 0) 1 else i ** (j - 1) * i 3 ** 2 // 9 extensionキーワードでより直感的に書ける https://scastie.scala-lang.org/ly6je4cNRweIh4lRbGSi6g
  4. 見せ算の実装はこんな感じ 19 extension (i: Int) def mise(j: Int): BigDecimal =

    (i min j, i max j) match case (6, 9) => 11 case (2, 5) => 1.1 case (1, 100) => 83 case (small, big) => if (small == big) 0 else big https://scastie.scala-lang.org/LrLMjihdQMejwFhiTvHphQ
  5. {}をちゃんとつけるとこんな感じ 22 extension (i: Int) { def mise(j: Int): BigDecimal

    = (i min j, i max j) match { case (6, 9) => 11 case (2, 5) => 1.1 case (1, 100) => 83 case (small, big) => if (small == big) 0 else big } }