必要な操作は「部分評価」と呼ばれます。これは、2 パラメーター関数を 2 つの 1 パラメーター関数に「カリー化」することに論理的に関連しています。
static class Extensions
{
static Func<A, R> PartiallyEvaluateRight<A, B, R>(this Func<A, B, R> f, B b)
{
return a => f(a, b);
}
}
...
Func<int, int, bool> isGreater = (x, y) => x > y;
Func<int, bool> isGreaterThanTwo = isGreater.PartiallyEvaluateRight(2);
isGreaterThanTwo
これで、where
節で使用できます。
最初の引数を指定したい場合は、簡単に書くことができますPartiallyEvaluateLeft
。
わかる?
カリー化操作 (部分的に左側に適用されます) は通常、次のように記述されます。
static class Extensions
{
static Func<A, Func<B, R>> Curry<A, B, R>(this Func<A, B, R> f)
{
return a => b => f(a, b);
}
}
そして今、工場を作ることができます:
Func<int, int, bool> greaterThan = (x, y) => x > y;
Func<int, Func<int, bool>> factory = greaterThan.Curry();
Func<int, bool> withTwo = factory(2); // makes y => 2 > y
それはすべて明確ですか?