2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でOption<T>型(再考)

Posted at

以前C#でOption<T>型を作りました。

しかし、これでは↓のような使い方ができません。

var v = from x in 1.ToOption()
        from y in 3.ToOption()
        select x + y;

そこで、↓のような拡張関数を追加します。

        //任意の型の実体を随意型の実体に変換する
        public static Option<T> ToOption<T>(this T self)
        {
            return Option.Return(self);
        }

        //随意型の実体から新しい随意型の実体を作成し、返す
        public static Option<S> SelectMany<T, S>(this Option<T> self, Func<T, Option<S>> f)
        {
            return self.Bind(f);
        }

        //随意型の実体から新しい随意型の実体を作成し、新しい随意型の実体から更に新しい随意型の実体を作成し、返す
        public static Option<R> SelectMany<T, S, R>(this Option<T> self, Func<T, Option<S>> f, Func<T, S, R> g)
        {
            return self.Bind((x) => f(x).Bind((y) => g(x, y).ToOption()));
        }

これでfromやselectが使えるようになりました。

わぁいOption<T>型プログラミングが捗るOption<T>型大好き。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?