简体   繁体   中英

How to create a single-dimensional, non-zero-based array in F#

I tried to create a single-dimensional, non-zero-based array in F#. I need such arrays for interoperability with code written in another programming language. Array2D.createBased function is intended to create a two-dimentional, non-zero-based array, but the F# language lacks Array.createBased function to create a single-dimentional, non-zero-based array. So, I tried to write my own function, but it does not work. Its code is here:

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

Please help!

These arrays are not normally supported in .NET ( http://msdn.microsoft.com/en-us/library/x836773a.aspx - thanks for link eis).

However, it is possible to provide a hackish solution that allow you to use the F# syntax.

Here is a very simple example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM