c# - 从集合中生成和组合函数

标签 c# functional-programming purely-functional

我想组成一个函数序列,当给定一个字符串时,它会通过所有创建的函数并生成修改后的字符串。 例如

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”并为每个字符串创建一个函数来删除该字符串。 当前的解决方案是有缺陷的,只应用最后一个函数,我似乎无法将其转换为委托(delegate),以便将它们与 += 运算符组合。

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

最佳答案

好吧,您的Select 为您提供了接受字符串并生成修改后的字符串的委托(delegate)集合,这样您就完成了一半。您所需要做的就是通过 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".

关于c# - 从集合中生成和组合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45531017/

相关文章:

c# - 属性路由 - 枚举未解析

c# - 选择具有多个 IP 时 HTTP 请求使用的 IP (.NET)

c# - 我怎么说不是,不是

c++ - 是否有类似于/等同于 Functional Java 的 C++ 库?

java - Java 8 中是否有用于参数检查的 requiredFalse 方法?

functional-programming - 在 fp-ts 的管道中混合 Either 和 TaskEither

scala coursera 函数式编程作业 FunSets

tree - 本地编辑纯功能树

kotlin - Unweave 序列,Kotlin 函数式/流式习语

c# - 在现有 MVC3 网站中使用 SharePoint 组件