F#: Creating Arrays

Intro

Creating arrays in F# can be done in multiple ways as I learned the hard way.

Initializing Arrays

Let’s first create a type:

type SomeType = SomeValue

Syntax

It’s important to note that arrays in F# have the following notation:

[| |]

There can be no spaces between “[” and “|”.

As a result, the following would be invalid:

let myArray = [ |SomeValue| ]

So we must correct this syntax error with the following:

let myArray = [|SomeValue|]

Next, let’s create an array of 10 elements:

let someArray1 = [| SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue |]

This code obviously has some duplication that we would like to reduce.

Let’s refine the initialization of the array to the following:

let someArray2 = [|for i in 0..9 -> SomeValue|]

An alternative method would be this:

let someArray3 = SomeValue |> Array.create 10

or…

let someArray3 = Array.create 10 SomeValue

Here’s the entire snippet:

type SomeType = SomeValue

let someArray1 = [| SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue
                    SomeValue |];;

let someArray2 = [|for i in 0..9 -> SomeValue|];;

let someArray3 = SomeValue |> Array.create 10;;

Conclusion

In conclusion, creating arrays in F# can be done in multiple ways.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: