Array initialization in F #

How to create and initialize an array in F # based on a given record type? Suppose I want to create an array of 100 records record1.

eg.

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

 let myArray = Array.init 100?

But it looks like Array.init is not allowing 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"} |]
+6
arrays initialization f #
source share
3 answers

This should do what you need. Hope this 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"}) 
+11
source share

You can also use Array.create , which creates an array of a given size with all its elements initialized to a specific value:

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

Take a look at this list of operations.

+11
source share

Or you can create a sequence instead of creating an array, for example:

 // 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 good thing about consistency, not an array, is that it creates elements as needed, not all at once. And it's just to go back and forth between sequences and arrays if you need to.

+2
source share

All Articles