2

動的に型指定された配列を返す関数を作成しようとしています。以下は、私が試した方法の 1 つの例です。

let rng = System.Random()

type ConvertType =
    | AsInts
    | AsFloat32s
    | AsFloats
    | AsInt64s

type InputType =
    | Ints of int[]
    | Float32s of float32[]
    | Floats of float[]
    | Int64s of int64[]

let genData : int -> int -> ConvertType -> InputType * int[] =
    fun (sCount:int) (rCount:int) (ct:ConvertType) ->
        let source = 
            match ct with
            | AsInts -> Array.init sCount (fun _ -> rng.Next()) |> Array.map (fun e -> int e) |> Ints
            | AsFloat32s -> Array.init sCount (fun _ -> rng.Next()) |> Array.map (fun e -> float32 e) |> Float32s
            | AsFloats -> Array.init sCount (fun _ -> rng.Next()) |> Array.map (fun e -> float e) |> Floats
            | AsInt64s -> Array.init sCount (fun _ -> rng.Next()) |> Array.map (fun e -> int64 e) |> Int64s
        let indices = Array.init rCount (fun _ -> rng.Next sCount) |> Array.sort
        source, indices

私が抱えている問題は、関数を使用するときに、配列を "InputType" ではなく float32[] などのプリミティブ型にする必要があることです。

また、インライン関数によって作成されたインターフェイスを介して、ジェネリックを使用してそれを試みました。私も思い通りに動作させることができませんでしたが、間違っていた可能性があります。

編集: 素晴らしい返信をありがとう、今日それを試してみる必要があります. 私は自分の問題を解決したので編集を追加していますが、私が望んでいた方法では解決しませんでした (つまり、答えのように)。したがって、これを見る可能性のある人のための参考までに、私は次のことを行いました。

let counts = [100; 1000; 10000]
let itCounts = [ 1000; 500; 200]

let helperFunct =
    fun (count:int) (numIt:int) (genData : int -> int -> ('T[] * int[] )) ->
        let c2 = int( count / 2 )
        let source, indices = genData count c2
        ....

[<Test>]
let ``int test case`` () =
    let genData sCount rCount =
        let source = Array.init sCount (fun _ -> rng.Next())
        let indices = Array.init rCount (fun _ -> rng.Next sCount) |> Array.sort
        source, indices

    (counts, itCounts) ||> List.Iter2 (fun s i -> helperFunct s i genData)
    .....

次に、進行中の各テストケースは次のようになります。

[<Test>]
let ``float test case`` () =
    let genData sCount rCount =
        let source = Array.init sCount (fun _ -> rng.Next()) |> Array.map (fun e -> float e)
        let indices = Array.init rCount (fun _ -> rng.Next sCount) |> Array.sort
        source, indices
    .....

しかし、私がこの質問をした理由は、テスト ケースごとに genData 関数を書き直さないようにしたかったからです。私の実際のコードでは、この一時的な解決策により、「helperFunct」内のいくつかのものを分割する必要がなくなりました。

4

1 に答える 1