如何将“ struct”与“ func”结合使用?

时间:2018-12-28 09:20:53

标签: c# curry

“ Curry”对我非常感兴趣,因此我尝试将其合并到C#“ Func”中。 有一个简单的练习来读取一些正值,然后对该系列求和,计数并取平均值。以下是第一次试用:

Func<int, Func<int, int>> CurriedSum = x => y => x + y;//Declare curryied sum
Func<int, int> CurriedCount = x => x + 1;//Declare counting
Console.Write("Please input the first number in a series: ");//Prompt
int inputValue = int.Parse(Console.ReadLine());//User's input
int sum = inputValue;//original sum = 1st value
int count = CurriedCount(0);//count from 0
do
{
    Console.Write("Please input the next number in a series (0 will exit):");//Prompt
    inputValue = int.Parse(Console.ReadLine());//User's input
    if (inputValue > 0)//Accept positive number only
    {
        sum = CurriedSum(inputValue)(sum);//Call curried function to sum
        count = CurriedCount(count);//Call function to count
        Console.Write($"=> Sum of {count} numbers is {sum}.");//Output
        Console.WriteLine($" Mean is {(float)resultInt/count}.");//Output
    }
} while (inputValue > 0);//loop until 0 or any negative number

此审判有效。但是,以下第二次尝试失败:

internal struct MyStruct
{
    public int Sum;
    public int Count;
    public float Mean;
}//located above static void Main(string[] args)

//Func<int, Func<int, MyStruct>> CurriedSumMean = x => y =>//wrong
Func<int, Func<MyStruct, MyStruct>> CurriedSumMean = x => y =>//*correct*
{
    MyStruct result;//no need to initialize
    //result.Sum = x + y;//wrong
    //result.Count++;//Error here!
    result.Sum = x + y.Sum;//*correct*
    result.Count = y.Count + 1;//*correct*
    result.Mean = result.Sum / result.Count;
    return result;
};//Calculate and return curried sum, counting and average
MyStruct series;//Declare a series
Console.Write("Please input the first number in a series: ");//Prompt
inputValue = int.Parse(Console.ReadLine());//User's input
series.Sum = inputValue;//original sum = 1st value
series.Count = 1;//count from 1
series.Mean = inputValue;//original average = 1st value
do
{
    Console.Write("Please input the next number in a series (0 will exit):");//Prompt
    inputValue = int.Parse(Console.ReadLine());//User's input
    if (inputValue > 0)//Accept positive number only
    {
        series = CurriedSumMean(inputValue)(series);//*it works!*
        Console.Write($"=> Sum of {series.Count} numbers is {series.Sum}.");//Output
        Console.WriteLine($" Mean is {series.Mean}.");//Output
    }
} while (inputValue > 0);//loop until 0 or any negative number

Visual Studio 2017发现两个错误。一个是result.Count ++。在咖喱函数函数CurriedSumMean中定义。另一个错误是series = CurriedSumMean(inputValue)(series)。

我如何正确使用“ struct”和“ Func”,尤其是柯里化? 非常感谢您的协助。

1 个答案:

答案 0 :(得分:2)

使用该对象之前,您必须对其进行初始化

MyStruct result = new MyStruct();

您不能将struct对象转换为整数。我想你应该使用series.Sum

series = CurriedSumMean(inputValue)(series.Sum);