Generic Arithmeticは、.NET言語でよくある問題だと思います。さまざまなアプローチを説明する記事がたくさんありますが、すぐに、あなたが投稿したソリューションに似た、私の説明をする別の記事を投稿します。
さて、あなたがそれを使うべきかどうか私に尋ねるなら、私は言うでしょう:あなたが何をしているのかを理解している限り、なぜそうではないのですか?部分的に本番環境で使用しており、まったく問題はありませんが、実行時のパフォーマンスを重視しているため、コンパイル時にすべてを解決するためにオーバーロードを使用しています。次に、コンパイル時間を短縮するために、基本的な数学演算子を同じ型で動作するように再定義します。そうしないと、型シグネチャが非常に複雑になり、コンパイルに時間がかかる場合があります。
考慮すべき点は他にもありますが、特定の問題については、サンプルコードを次に示します。
open System.Numerics
type FromInt = FromInt with
static member ($) (FromInt, _:sbyte ) = fun (x:int) -> sbyte x
static member ($) (FromInt, _:int16 ) = fun (x:int) -> int16 x
static member ($) (FromInt, _:int32 ) = id
static member ($) (FromInt, _:float ) = fun (x:int) -> float x
static member ($) (FromInt, _:float32 ) = fun (x:int) -> float32 x
static member ($) (FromInt, _:int64 ) = fun (x:int) -> int64 x
static member ($) (FromInt, _:nativeint ) = fun (x:int) -> nativeint x
static member ($) (FromInt, _:byte ) = fun (x:int) -> byte x
static member ($) (FromInt, _:uint16 ) = fun (x:int) -> uint16 x
static member ($) (FromInt, _:char ) = fun (x:int) -> char x
static member ($) (FromInt, _:uint32 ) = fun (x:int) -> uint32 x
static member ($) (FromInt, _:uint64 ) = fun (x:int) -> uint64 x
static member ($) (FromInt, _:unativeint) = fun (x:int) -> unativeint x
static member ($) (FromInt, _:bigint ) = fun (x:int) -> bigint x
static member ($) (FromInt, _:decimal ) = fun (x:int) -> decimal x
static member ($) (FromInt, _:Complex ) = fun (x:int) -> Complex(float x,0.0)
let inline fromInt (a:int) : ^t = (FromInt $ Unchecked.defaultof< ^t>) a
module NumericLiteralG =
let inline FromZero() =LanguagePrimitives.GenericZero
let inline FromOne() = LanguagePrimitives.GenericOne
let inline FromInt32 (i:int) = fromInt i
// This will reduce the number of types inferred, will reduce compile time too.
let inline (+) (a:^t) (b:^t) : ^t = a + b
let inline (-) (a:^t) (b:^t) : ^t = a - b
let inline (*) (a:^t) (b:^t) : ^t = a * b
let inline (/) (a:^t) (b:^t) : ^t = a / b
let inline (~-) (a:^t) : ^t = -a
let inline halfSquare num =
let res = num / 2G
res * res
let solve1 = halfSquare 5I
let solve2 = halfSquare 5.0
let solve3 = halfSquare 5uy
// Define more generic math functions.