8
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?

Elixir使いがC#を学ぶ 〜関数パターンマッチ風に書きたい〜

Last updated at Posted at 2025-12-19

C#でも関数パターンマッチを使いたいです
結論は無理でした

だが、関数パターンマッチに慣れていると書き方を近くしたい
関数定義でswitchを使うと表現を近くすることは可能でした

Elixirの関数パターンマッチ例

defmodule Ymn2 do
  def next(1, 2), do: "OK"
  def next(2, 3), do: "OK"
  def next(_, _), do: "NG"
end

Ymn2.next(1, 2)
|> IO.inspect()

Ymn2.next(2, 3)
|> IO.inspect()

Ymn2.next(2, 1)
|> IO.inspect()

# 結果
"OK"
"OK"
"NG"

C#で再現

Ymn2.Next(1, 2)
 .Inspect();

Ymn2.Next(2, 3)
 .Inspect();

Ymn2.Next(2, 1)
 .Inspect();


public static class Ymn2
{
    public static string Next(int x, int y) => (x, y) switch
    {
        (1, 2) => "OK",
        (2, 3) => "OK",
        _ => "NG"
    };
}

// 結果
"OK"
"OK"
"NG"

同じ結果が可能でした

C#のInspectは自作です

using System.Text.Json;

public static class Ymn
{
    public static T Inspect<T>(this T value)
    {
        var json = JsonSerializer.Serialize(value);
        Console.WriteLine(json);

        return value;
    }
}

こちらは↓こコラムで作りました

では、良きC#ライフ!

8
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
8
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?