4 ms·
> Monoid T AddAll<T>(params T[] elements) where T : IMonoid<T> => elements switch { [] => T.Zero, [var first, ..var rest] => first + AddAl
by delta_p_delta_x 4y ago
> Monoid
T AddAll<T>(params T[] elements) where T : IMonoid<T> =>
elements switch
{
[] => T.Zero,
[var first, ..var rest] => first + AddAll<T>(rest),
};
It is remarkable how functional C# has become. Not that it wasn't very functional already, what with LINQ and its (much more powerful than Java) generics but the above example really hammers home how much FP has inspired C#, on top of Ocaml's influence on C# generics[0].
[0]: https://github.com/ocaml/cwn-data/blob/9ee93e99d984b3f922e2566eff5277233a305bfc/2006.11.21.text#L40 https://github.com/ocaml/cwn-data/blob/9ee93e99d984b3f922e25...
- vyrotek 4y agoI saw that and immediately thought, "Someone put F# in my C#!". Looks great.
- WorldMaker 4y ago> its (much more powerful than Java) generics Yeah, it's also interesting to point out how useful to FP C# 11's further improvements to generics are. Generic Math, which the IMonoid<T> in this example is a part of explaining a small related piece of (static abstract interfaces), is another place where C# is improving generics (further beyond Java). The list of interfaces in the much expanded System.Numerics namespace where most of the raw implementation of Generic Math lives should look quite interesting, if not familiar, to many FP developers: https://learn.microsoft.com/en-us/dotnet/api/system.numerics?view=net-7.0 https://learn.microsoft.com/en-us/dotnet/api/system.numerics... It will be interesting to see where libraries take Generic Math.
- david_allison 4y agoAlthough seldom used, C# has allowed for Haskell-style monadic comprehension syntax for decades via extension methods. It's very strong functionally var paymentId = from joshIban in processor.GetIban("josh") // fails from olenaIban in processor.GetIban("olena") // not executed from paymentId in processor.SendPayment(joshIban, olenaIban, 100) select paymentId; https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-What-is-LINQ-really%3F https://github.com/louthy/language-ext/wiki/Thinking-Functio...
- ziml77 4y agoIt's been going that way since LINQ and I'm happy every time they move a bit more functional. I don't want my C# to be purely functional, but I love being able to choose to use functional constructs when I feel they work better.