LoginSignup
8
6

More than 5 years have passed since last update.

C#で関数合成

Last updated at Posted at 2014-08-31

C#でFuncを使って関数合成みたいなことをする。

C#は.NET2.0からジェネリクス、.NET3.0からラムダ式と拡張メソッドを使うことができるようになりました。

何番煎じか分かりませんが、今回はこれらを使って関数合成っぽいものを実装します。

実装

とりあえず実装

func.cs
namespace System
{
    public static class Func
    {
        public static Func<T, V> andThen<T, U, V>(this Func<T, U> f, Func<U, V> g)
        {
            return a => g(f(a));
        }
    }
}

これだけです。

使い方

usage.cs
using System;
using System.Console;

class Piyo
{
    public static void Main()
    {
        Func<int, string> intToString = i => i.toString();
        Func<string, string> repeat = str => str + str;
        var ans = intToString.andThen(repeat)(10);
        Console.WriteLine(ans); // "1010"
    }
}

解説

FuncとFuncを合成して、1つのFuncにします。
先の例では、

intを受け取ってtoString()して返すintToString

stringを受け取って二度繰り返して返すrepeatを

合成することによって

intを受け取ってtoString()して二度繰り返すFuncを作っています。

このように処理を分割、合成することで、コードの再利用性が上がります。

またメソッドの中でFuncを作る場合はスコープを制限することができます。

注意?

Func AとFunc Bを合成したFuncを実行した時に、Aで例外が投げられると、Bでキャッチされず合成されたFuncの外に例外を投げます。従って、この方法では、「Aで投げられた例外をBでキャッチする」ということはできません。
(Aで投げられた例外をBでキャッチする方法をご存じの方がいらっしゃいましたら教えてください)

あと、Funcにした時のパフォーマンスはどのくらいになるのかも不明です。これもご存じの方がいらっしゃいましたら教えてください。

8
6
1

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
6