2016-01-04 29 views
4

我想将一些Python转换为F#,特别是numpy.random.randn从一个函数返回不同尺寸的数组;在F#中可能吗?

该函数接受可变数量的int参数,并根据参数的数量返回不同维度的数组。

我认为这是不可能的,因为一个不能返回不同类型的函数(int[]int[][]int[][][]等),除非它们是歧视工会的一部分,但要承诺一个解决办法之前,以确保。

的健全性检查:

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

原因错误:

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

expression感:[| 2 |], [| 3 |]
int参照1 [| 1 |]
1类型是不一样的[| 2 |], [| 3 |]

TLDR;从交互式Python会话

numpy.random.randn

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

Return a sample (or samples) from the “standard normal” distribution.

If positive, int_like or int-convertible arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1 (if any of the d_i are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided.

例子:

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

代码为Neural Networks and Deep Learning,并因为这些值需要可变因为性能原因,使用不可变列表是不是一种选择。

+2

你可能会需要使用DU –

+0

可能有不同的解决方法比杜:成员self.differntarrays([]尺寸:对象[]):对象[] - 请注意它返回的对象[]。这可能会导致下游出现问题,因此尚未提交。 –

+0

注意:[如何使函数返回fsharp中真正不同的类型?](http://stackoverflow.com/q/24218051/1243762) –

回答

4

你是正确的 - 浮float[]的阵列是一种不同的类型浮标的数组的数组
float[][]或浮float[,]的2D阵列,因此可以不写返回一个或另一个根据输入自变量的函数。

如果你想做一些像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) |] 
1

虽然托马斯超限超载使用的建议可能是最好的,.NET数组享有共同的分型:System.Array。所以你想要的是可能的。

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

谢谢。我总是欣赏不同的答案,因为它会导致对未来问题的想法,并保持思想的工作。 –

相关问题