tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Sum function using “generic math” and head and tail functions

17 Jan 2023 1 mins C#

As promised in previous blog post. Let’s implement that sum function using generic math from C# 11.

static T Sum<T>(ListRangeWrapper<T> list) where T : INumber<T>
    => list switch
    {
        [] => T.Zero,
        [var head, .. var tail] => head + Sum(tail),
    };

Except for the T.Zero, it’s the same code. But it’s still nice to be able to do it.

But now simply calling the function like in previous post doesn’t work.

var list = new List<int>() { 1, 2, 3 };
Sum(list);

The type arguments for method 'Sum<T>(ListRangeWrapper<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Well, maybe in the end I will have to add the overload anyway (or stop (ab)using the implicit casting).

static T Sum<T>(List<T> list) where T : INumber<T> => Sum((ListRangeWrapper<T>)list);

Of course, specifying the type explicitly (Sum<int>(list)) would work too. It’s just not slick, I think.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.