如何在F#中创建一个非零的基于数组的数组

时间:2013-04-12 08:35:07

标签: arrays f#

我尝试在F#中创建一个基于非零的单维数组。 我需要这样的数组来与用另一种编程语言编写的代码进行互操作。 Array2D.createBased函数用于创建一个二维,非零的数组,但F#语言缺少Array.createBased函数来创建一个单维,非零的数组。所以,我试着编写自己的函数,但它不起作用。它的代码在这里:

let createBased base1 length1 (initial : 'a) =           
       // the problem is here: System.Array ('a [*]) is not convertible to array ('a []), 
       // so InvalidCastException error is raised at run-time
       let A = Array.CreateInstance (typeof<'a>, [| length1 |], [| base1 |]) :?> 'a [] 

       for i in A.GetLowerBound(0) .. A.GetUpperBound(0) do A.[i] <- initial 
       A

请帮忙!

1 个答案:

答案 0 :(得分:1)

.NET中通常不支持这些数组(http://msdn.microsoft.com/en-us/library/x836773a.aspx - 感谢链接e-i-s)。

但是,可以提供一种允许您使用F#语法的hackish解决方案。

这是一个非常简单的例子

open System
type Hack() =
    let A = Array.CreateInstance (typeof<int>, [| 5 |], [| 5 |])
    member x.Item with get(y:int) = A.GetValue(y) and set (v:int) (y:int) = A.SetValue(y,v)

let a = new Hack()
printfn "%A" (a.[8])
a.[8]<-1
printfn "%A" (a.[8])