2016-01-04 31 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

謝謝。我總是欣賞不同的答案,因爲它會導致對未來問題的想法,並保持思想的工作。 –

相關問題