我想组成一个函数序列,当给定一个字符串时,它会通过所有创建的函数并生成修改后的字符串。 例如
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/