从集合中生成和组合函数
Generate and combine functions from collections
我想编写一系列函数,当给定一个字符串时,它会通过所有已创建的函数并生成修改后的字符串。
例如
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" 并为每个字符串创建一个函数来删除该字符串。
目前的解决方案是有缺陷的,只适用于最后一个功能,我似乎无法将其转换为委托,以便将它们与 +=
运算符结合起来。
或者有更好的功能方案吗?
好吧,您的 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".
我真的不知道什么算作 "functional"。我假设您不想使用任何流量控制结构。
这样更简单,你不觉得吗?
string[] arr = {"po", "ro", "mo", "do"};
arr.Aggregate("pomodoroX", (x, y) => x.Replace(y, ""))
我想编写一系列函数,当给定一个字符串时,它会通过所有已创建的函数并生成修改后的字符串。 例如
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" 并为每个字符串创建一个函数来删除该字符串。
目前的解决方案是有缺陷的,只适用于最后一个功能,我似乎无法将其转换为委托,以便将它们与 +=
运算符结合起来。
或者有更好的功能方案吗?
好吧,您的 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".
我真的不知道什么算作 "functional"。我假设您不想使用任何流量控制结构。
这样更简单,你不觉得吗?
string[] arr = {"po", "ro", "mo", "do"};
arr.Aggregate("pomodoroX", (x, y) => x.Replace(y, ""))