C# 定义函数并以部分应用为委托

问题描述 投票:0回答:4

考虑以下方法:

int Foo(string st, float x, int j)
{
    ...
}

现在我想通过提供参数

Func<float, int>
st
的值将其包装在
j
类型的委托中。但我不知道语法。有人可以帮忙吗?

这就是想法(可能看起来有点 Haskell 风格):

Func<float, int> myDelegate = new Func<float, int>(Foo("myString", _ , 42));
// by providing values for st and j, only x is left as a parameter and return value is int
c# delegates partial-application
4个回答
8
投票

这应该可以解决问题:

Func<float, int> f = (x) => { return Foo("myString", x, 42); };

按照您想要的方式部分应用函数目前只能在 F# 中实现,而不能在 C# 中实现。


4
投票

部分应用没有特定的语法。您可以通过以下方式进行模拟

Func<int, int, int, int> multiply = (a, b, c) => a*b*c;
Func<int, int, int> multiplyPartialApplication = (a, b) => multiply(a, b, 100);

请注意,这可能不是您想要在资源受限的应用程序中执行的操作,因为它会导致额外的分配。


1
投票

我相信这种替代方案是最灵活和最直接的,尽管如果不习惯这种练习的话会有些困难。

// Given
int Foo(string st, float x, int j) => default;

// Inlined partial application
Func<string, int, Func<float, int>> applyFoo
    = (st, j) => (x) => Foo(st, x, j);
// Or as part of a function
Func<float, int> ApplyFoo(string st, int j)
    => (x) => Foo(st, x, j);

// Usage
var bar = 42;
var appliedFoo = applyFoo("foo", bar);
var result = appliedFoo(12.34);
// Or
var result = applyFoo("foo", bar)(12.34);

参数顺序的选择在这种情况下会有所不同,因为如果

Foo
被定义为
int Foo(string st, int j, float x)
,那么处理起来会更简单(通过 pApply 助手),因为创建位置部分非常容易应用助手。


0
投票

我希望这个解决方案有帮助:

    public static class FunctionExtensions
    {
        public static Func<T1, Func<T2, Func<T3, TResult>>> Curried<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> func)
        {
            return x1 => x2 => x3 => func(x1, x2, x3);
        }
    }

    //you create your delegate
    var myDelegate = new Func<string, int, float, int>((st, j, x) => Foo(st, x, j)).Curried();

    //call it with your two specified parameters where you have only them and pass the returned function that expects your float parameter
    var returnedFunction = myDelegate("myString")(42);

    //call the returned function eventually with your float parameter
    var result = returnedFunction(0f);
© www.soinside.com 2019 - 2024. All rights reserved.