gpt4 book ai didi

c# - 将多个参数传递给谓词,函数式编程

转载 作者:行者123 更新时间:2023-12-05 03:06:31 24 4
gpt4 key购买 nike

我正在努力更好地理解函数式编程。提供了下面的例子,这个例子创建了一个谓词 lambda。然后创建一个静态方法来计算通过谓词条件的项目数。

public Predicate<string> longWords = (x) => x.Length > 10;

public static int Count<T>(T[] array, Predicate<T> predicate, int counter)
{
for (int i = 0; i < array.Length; i++)
{
if (predicate(array[i]))
{
counter++;
}
}

return counter;
}

我想让这个解决方案遵循 Referential Transparency该原则指出您只能通过查看其参数的值来确定应用该函数的结果。

不幸的是longWords没有告诉我长单词的真正含义,我需要将参数传递给 longWords告诉它使函数成为长字的长度,即不是硬编码“10”。

Predicates只接受一个参数,使longWords需要 Predicate<Tuple<string,int>> ,伴随着它的挑战。

下面是我试图找到解决方案的尝试,以及导致的两条错误消息。

public class BaseFunctions
{
public Predicate<Tuple<string, int>> longWords = (x) => x.Item1.Length > x.Item2;

public static int Count<T>(T[] array, Predicate<T> predicate, int counter)
{
for (int i = 0; i < array.Length; i++)
{
/// error below: Cannot convert from 'T' to 'string'
/// in the example provided predicate(array[i]) worked fine when the predicate had only string type
if (predicate(new Tuple<string, int>(array[i], 10)))
{
counter++;
}
}
return counter;
}
}

它的用法

 BaseFunctions b = new BaseFunctions();
string[] text = ["This is a really long string", "Not 10"];
/// also error below on BaseFunctions.Count 'The type arguments for method BaseFunctions.Count<T>(T[], Predicate<T>, int) cannot be inferred from the usage. Try specifying the arguments explicitly
Console.WriteLine(BaseFunctions.Count(text, b.longWords, 0).ToString());
Console.ReadLine();

最佳答案

我会:

public Func<string, int, bool> longWords = (str, number) => str.Length > number;

代替:

public Predicate<Tuple<string, int>> longWords = (x) => x.Item1.Length > x.Item2;

这仅仅是因为我相信使用一个接受 stringint 然后返回一个 bool 的函数会更容易到一个谓词,该谓词采用 stringint 的元组并返回 bool。加上这个版本的元组类型使用起来很麻烦。如果您使用的是 C#7 及更高版本,请考虑新的元组类型。

然后更改方法签名:

public static int Count<T>(T[] array, Predicate<T> predicate, int counter)

到:

public static int Count<T>(T[] array, Func<T, int, bool> predicate, int counter)

为了适应上述委托(delegate)类型的变化。

然后 if 条件需要更改为:

if (predicate(new Tuple<string, int>(array[i], 10)))

到:

if (predicate(array[i], 10))

为了适应上述委托(delegate)类型的变化。

另外,请注意,在 C# 中,您需要像这样定义数组:

string[] text = { "This is a really long string", "Not 10" };

而不是 [ ] 大括号。

现在您的使用代码变为:

BaseFunctions b = new BaseFunctions();
string[] text = { "This is a really long string", "Not 10" };

Console.WriteLine(BaseFunctions.Count(text, b.longWords, 0).ToString());
Console.ReadLine();

关于c# - 将多个参数传递给谓词,函数式编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com