0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

関数型PG言語に倣う:パターンマッチとは

Last updated at Posted at 2024-12-06
1 / 8

関数型PG言語に習う:パターンマッチとは

  • 分岐の表記方法の1つ
  • ifではネスト地獄になる複雑な条件をシンプルに書ける魔法の記法!

サンプル

配列のパターンマッチ

case list of
  []     -> "(空=要素数0の場合)"
  (e:[]) -> "(要素数1で、その要素をeという変数に格納)"
  _      -> "その他のケース"

タプルとの併用が協力

  • タプルというデータ構造:複数の値を束ねる、異なる型でもOK
  • C#にもある!
  • ("jabaraster", 20251110)
case (person.isAdmin, person.name) of
  (true, "jabaraster") -> "..."
  (false, _)           -> "..."

パターンが網羅されていないときの挙動

  • エラーになって欲しい
  • 実際、ElmやHaskellはエラーになる

他の言語でのパターンマッチ

  • Scalar
  • Haskell:ほぼElmと同じ

C#での疑似パターンマッチ -switchを使う

switch ((father is not null, mother is not null))
{
    case (true, true):
        // 父母どちらも存在するときの処理
        break;
    case (true, false):
        // 父のみ存在するときの処理
        break;
    default:
        // その他の場合の処理
        break;
}
  • C#のswitchは非常に奥が深いのでドキュメント見てみるのがおすすめ

最後に

  • パターンマッチが使える言語が限られるが、知っておくことが重要
  • C#では似たような書き方ができる
  • しかし堅牢性はElmやHaskellに劣るのでその点は注意
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?