DEV Community

Discussion on: Using the new INumber type to generify math functions in .NET 7

Collapse
 
armousness profile image
Sean Williams • Edited

This is a nice change, but it should be pointed out, this will likely still involve casting all your numbers to double. Just going off the syntax, T in T CartValue(T[] numbers) will always resolve to a single type for a particular call, meaning that all the elements in your array have one type. This just saves you from having to rewrite CartValue for different numeric types—it almost certainly does not smuggle in heterogeneous arrays.

I know this is just your example program, and example programs are always contrived. After all, business software probably shouldn't be polymorphic on money representation. And in my opinion, you shouldn't use doubles to represent money.

That said, this is a nice addition, actually something I'd despaired a bit about not having before. Particularly the inclusion of T.Zero.

Collapse
 
pbouillon profile image
Pierre Bouillon

You are absolutely right, thanks for pointing that!

Indeed my example might not have been the most explicit one, I should have talked about summing only taxes (double) to avoid confusion

Collapse
 
armousness profile image
Sean Williams

The reason I like this is that it lets you turn fold into sum easily, something like,

let fold collection initial f =
    let mutable res = initial
    for item in collection do
        res <- f res item
    res

let sum (numbers: #INumber<'t>) = fold numbers (INumber<'t>.Zero) (+)

let product (numbers: #INumber<'t>) = fold numbers (INumber<'t>.One) (*)
Enter fullscreen mode Exit fullscreen mode

or however that syntax is going to work out. Then there are a lot of other things you can do with that sort of pattern. Being able to write more complex stuff, like weighted average and standard deviation, is pretty hot.