arrays - 从一个函数返回不同维度的数组;在 F# 中可能吗?

标签 arrays f#

我正在尝试将一些 Python 转换为 F#,特别是 numpy.random.randn .

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

我相信这是不可能的,因为一个函数不能返回不同类型( int[]int[][]int[][][] 等),除非它们是受歧视联合的一部分,但在 promise 之前要确定一种解决方法。

健全性检查:

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;

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.



交互式 python session 的示例:
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并且由于出于性能原因这些值需要可变,因此不能选择使用不可变列表。

最佳答案

你是对的 - 浮点数组 float[]与浮点数组的数组类型不同float[][]或二维浮点数组 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) |]

关于arrays - 从一个函数返回不同维度的数组;在 F# 中可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599909/

相关文章:

java - Java将十进制图像转换为灰度图像

ios - 未保存 PDF 注释

f# - 我可以在 F# Interactive 中获取没有内容的值的推断类型吗?

list - 表示一个 nil 列表和/或一个 list(nil)

f# - F#在实际处理int64时假设int

f# - FParsec:回溯 `sepBy`

javascript - 在 Neo4j 中以对象数组形式检索数据

javascript - 对 Array.prototype.reduce 的 polyfill 感到困惑

c++ - 为什么我的代码输出不正确的结果?整数溢出?

f# - 如何在 F# 中使用 LINQ to XML 提取特定标签?