Returning arrays of different dimensions from one function; is it possible in F#?

后端 未结 2 1817
别跟我提以往
别跟我提以往 2020-12-19 17:21

I am trying to convert some Python to F#, specifically numpy.random.randn.

The function takes a variable number of int arguments and returns arrays of different dim

相关标签:
2条回答
  • 2020-12-19 17:54

    Although Tomas' suggestion to use overloading is probably best, .NET arrays do share a common sub-type: System.Array. So what you want is possible.

    member self.differntarrays ([<ParamArray>] dimensions: Object[]) : Array =
        match dimensions with
        | [| dim1 |] ->      
             [| 
                1 
             |] :> _
        | [| dim1; dim2 |] -> 
            [|
               [| 2 |], 
               [| 3 |] 
            |] :> _
        | _ -> failwith "error"
    
    0 讨论(0)
  • 2020-12-19 17:55

    You are correct - an array of floats float[] is a different type than array of arrays of floats
    float[][] or 2D array of floats float[,] and so you cannot write a function that returns one or the other depending on the input argument.

    If you wanted to do something like the Python's rand, you could write an overloaded method:

    type Random() = 
      static let rnd = System.Random()
      static member Rand(n) = [| for i in 1 .. n -> rnd.NextDouble() |]
      static member Rand(n1, n2) = [| for i in 1 .. n1 -> Random.Rand(n2) |]
      static member Rand(n1, n2, n3) = [| for i in 1 .. n1 -> Random.Rand(n2, n3) |]
    
    0 讨论(0)
提交回复
热议问题