a)はあなたがそれらに適用する演算子/メソッドをサポートし、既に使用しているタイプは、この場合、
は、単にあなたの関数の前にinline
を追加するには、問題の3つのアプローチは基本的にあります。そして、)
B幸せであるあなたは、あなたが拡張メソッドを使用せずに関数定義で新しいメンバーを定義することができますです
を使用しているタイプを完全に制御できます。この場合、あなたはこのかなり奇妙探し構文
let inline mult (x:^T) (y:^T) = (^T : (static member Mult: ^T -> ^T -> ^T) (x, y))
でジェネリック型の制約を使用して
type MyInt16 = MyInt16 of int
with
static member Mult(x, y) =
match x,y with
| MyInt16 x', MyInt16 y' -> MyInt16 (x' * y')
type MyInt32 = MyInt32 of int
with
static member Mult(x, y) =
match x,y with
| MyInt32 x', MyInt32 y' -> MyInt32 (x' * y')
とインライン関数必要なものを実装する各クラスのメソッドを定義して、あなたは
let a = MyInt16 2
let b = MyInt16 3
let c = mult a b
をテスト
これは機能します。異なるタイプを使用すると何が起こるかを確認してください。
let d = mult a (MyInt32 3)
上記のエラーはあなたに表示されます。
C)あなたがタイプ内のメソッドを定義することはできませんが、あなたが拡張メソッドを使用する必要がありますです、あなたのタイプ
を完全に制御を持っていません。拡張メソッドの問題点は、汎用タイプの制約を使用するインライン関数を持つ を使用できないことです。あなたがより良いparameter approach I described here
type MultParam =
| MyInt16Param of System.Int16
| MyInt32Param of System.Int32
with
static member op_Implicit(x: System.Int16) = MyInt16Param x
static member op_Implicit(x: System.Int32) = MyInt32Param x
にフォールバックこの場合、その後、あなたのラッパー型
let inline (!>) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x)
と実装を追加するにあなたの着信の種類を変換し、一般的な制約に再びインライン関数を定義します。我々は
let inline mult' (x: ^T) (y: ^T) : ^T =
let x' = !> x
let y' = !> y
let r =
match x', y' with
| MyInt16Param x'', MyInt16Param y'' -> x'' * y'' |> box
| MyInt32Param x'', MyInt32Param y'' -> x'' * y'' |> box
| _ -> failwith "Not possible"
r :?> _
パターンマッチングを使用する必要があるとして、この時間ビットwordierは、今度は、この作品再び
let e = mult' (int16(2)) (int16(3))
をテストしてみましょう。異なるタイプを使用すると何が起こるかを見てみましょう。
let f = mult' (int16(2)) (int32(3))
もう一度エラーがあります。
オプションB)は、基本的に
オプションc)のように多型変異体
これは、[制約](https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/generics/constraints)で達成できるかもしれない - それがしたいかどうかしかし、私はわかりません。 –