简体   繁体   English

F#中的数组初始化

[英]Array initialization in F#

How do I create and initialize an array in F# based on a given record type? 如何根据给定的记录类型在F#中创建和初始化数组? Suppose I want to create an Array of 100 record1 records. 假设我想创建一个包含100条记录1的数组。

eg 例如

type record1 = {
  value1:string;
  value2:string
}

let myArray = Array.init 100 ?

But it appears the Array.init does not allow for this, is there a way to do this? 但似乎Array.init不允许这样做,有没有办法做到这一点?

Edited to add: 编辑添加:

Of course I could do something like this: 当然我可以这样做:

let myArray = [|for i in 0..99 -> { value1="x"; value2="y" }|]

This should do what you need. 这应该做你需要的。 Hope it helps. 希望能帮助到你。

type record1 = {
  value1:string;
  value2:string
}

let myArray  = Array.init 100 (fun x -> {value1 = "x"; value2 = "y"})

or using Generics 或使用泛型

let myArray  = Array.init<record1> 100 (fun x -> {value1 = "x"; value2 = "y"})

You can use also Array.create , which creates an array of a given size, with all its elements initialized to a defined value: 您还可以使用Array.create ,它创建一个给定大小的数组,并将其所有元素初始化为定义的值:

let myArray  = Array.create 100 {value1="x"; value2="y"}

Give a look to this list of array operations . 看一下这个数组操作列表。

Or you can create a sequence, instead of creating an array, like this: 或者您可以创建一个序列,而不是创建一个数组,如下所示:

// nItems, given n and an item, returns a sequence of item repeated n times
let rec nItems n item = 
  seq {
    match n with
    | n when n > 0 -> yield item; yield! nItems (n - 1) item
    | _ -> ()
  }

type Fnord =
 { foo: int }

printfn "%A" (nItems 99999999 {foo = 3})
// seq [{foo = 3;}; {foo = 3;}; {foo = 3;}; {foo = 3;}; ...]

printfn "%A" (nItems 3 3 |> Seq.toArray)
[|3; 3; 3|]

The nice thing about the sequence, instead of an array, is that it creates items as you need them, rather than all at once. 关于序列而不是数组的好处是它可以根据需要创建项目,而不是一次创建项目。 And it's simple to go back and forth between sequences and arrays if you need to. 如果需要,在序列和数组之间来回移动很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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