Skip to content

Case class について便利なテクニック #2

Description

@ryuhei-mori

行列を表現するのに case class を使っている人が多いですが、行列の成分を受けとるのに選択肢が1つだけのパターンマッチを使っている人が多いです。そのような場合には構造化代入(destructing binding)というテクニックが使えます。例えば

case class Matrix(a11: BigInt, a12: BigInt, a21: BigInt, a22: BigInt)
def mult(a: Matrix, b: Matrix): Matrix = {
  a match = { case Matrix(x, y, z, w) => /* なにか計算 */ }
}

というプログラムは

def mult(a: Matrix, b: Matrix): Matrix = {
  val Matrix(x, y, z, w) = a
  /* なにか計算 */
}

と書くことができます。また case class のメンバ変数には c.a22 のようにアクセスすることもできます。ここで cMatrix 型とします。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions