How do I create and initialize an array in F# based on a given record type?
Suppose I want to create an Array of 100 record1 records.
e.g.
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?
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:
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.