【问题标题】:Generate and combine functions from collections从集合中生成和组合函数
【发布时间】:2018-01-13 19:43:15
【问题描述】:

我想编写一个函数序列,当给定一个字符串时,将它传递给所有创建的函数并生成一个修改后的字符串。 例如

string[] arr = {"po", "ro", "mo", "do"};

var modify = "pomodoroX";
foreach (var token in arr)
{
    modify = modify.Replace(token, "");
}
Console.WriteLine(modify); // Output: X

这解决了问题,但我对功能解决方案感兴趣:

Console.WriteLine(
    arr.Select<string, Func<string, string>>(val => (s1 => s1.Replace(val, string.Empty)))
       .Aggregate((fn1, fn2) => fn1 += fn2)
       .Invoke("pomodoroX")
); 
   // Output: pomoroX -> Only last element applied because: 
   // the functions are not getting combined.

所以基本上,取数组“arr”并为每个字符串创建一个删除该字符串的函数。 当前的解决方案存在缺陷,仅应用最后一个函数,我似乎无法将其转换为委托,以便将它们与 += 运算符结合起来。

或者有更好的功能解决方案吗?

【问题讨论】:

    标签: c# functional-programming purely-functional


    【解决方案1】:

    好吧,您的Select 为您提供了接受字符串并生成修改后的字符串的委托集合,所以您已经完成了一半。您只需通过Aggregate 将它们链接在一起 - 您的操作方式如下:

    string[] arr = { "po", "ro", "mo", "do" };
    
    string result = arr
        // Produce our collection of delegates which take in the string,
        // apply the appropriate modification and return the result.
        .Select<string, Func<string, string>>(val => s1 => s1.Replace(val, string.Empty))
        // Chain the delegates together so that the first one is invoked
        // on the input, and each subsequent one - on the result of
        // the invocation of the previous delegate in the chain.
        // fn1 and fn2 are both Func<string, string>.
        .Aggregate((fn1, fn2) => s => fn2(fn1(s)))
        .Invoke("pomodoroX");
    
    Console.WriteLine(result); // Prints "X".
    

    【讨论】:

    • 非常感谢朋友! Soo 函数组合就像数学 fn(fn2(param)) 一样。
    【解决方案2】:

    我真的不知道什么才是“功能性”。我假设您不想使用任何流控制结构。

    这更简单,你不觉得吗?

    string[] arr = {"po", "ro", "mo", "do"};
    arr.Aggregate("pomodoroX", (x, y) => x.Replace(y, ""))
    

    【讨论】:

    • 酷,刚学c#,太强大了。 (我仍在思考 Java 方式)。对于功能性,我的意思是没有我不断在外部修改的变量。这样,我们通过一系列函数传递它,每个函数都进行修改并将其作为参数传递给另一个。
    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多