Returned arrays of different dimensions from one function; is this possible in f #?

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 dimensions based on the number of arguments.

I believe that this is impossible, because there can not be a function that returns different types ( int[], int[][], int[][][]etc.), if they are not part of the demarcated union, but want to be sure before you go to the workarounds.

Health Check:

member self.differntarrays ([<ParamArray>] dimensions: Object[]) =
    match dimensions with
    | [| dim1 |] ->      
         [| 
            1 
         |]
    | [| dim1; dim2 |] -> 
        [|
           [| 2 |], 
           [| 3 |] 
        |]
    | _ -> failwith "error"

causes an error:

This expression was expected to have type  
    int    
but here has type  
    'a * 'b 

c expression: [| 2 |], [| 3 |]
and int, referring to 1 in [| 1 |]
i.e. type 1does not match type[| 2 |], [| 3 |]

TL; DR;

numpy.random.randn

numpy.random.randn (d0, d1, ..., dn)

( ) .

, int_like int-convertable , randn (d0, d1,..., dn), , "" () 0 1 ( - d_i , ). , .

python:

np.random.randn(1)  - array([-0.28613356])
np.random.randn(2)  - array([-1.7390449 ,  1.03585894]) 
np.random.randn(1,1)- array([[ 0.04090027]])
np.random.randn(2,3)- array([[-0.16891324,  1.05519898, 0.91673992],  
                             [ 0.86297031,  0.68029926, -1.0323683 ]])

, , .

+4
2

- floats float[] - ,
float[][] 2D- float[,], , .

- Python rand, :

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) |]
+4

Tomas , , ,.NET- : System.Array. , .

member self.differntarrays ([<ParamArray>] dimensions: Object[]) : Array =
    match dimensions with
    | [| dim1 |] ->      
         [| 
            1 
         |] :> _
    | [| dim1; dim2 |] -> 
        [|
           [| 2 |], 
           [| 3 |] 
        |] :> _
    | _ -> failwith "error"
+1

Source: https://habr.com/ru/post/1622823/


All Articles