F# – Arrays

Next in the F# language, I would like to go over arrays.

I went over loops in my previous post, which I will be using which our arrays, so please take a look at that first if you haven’t learned how to do a for statement.  One thing to remember about Arrays is that they are mutable by default, so you don’t have to use the mutable keyword to indicate that you would like to update the values.

The syntax for declaring an array seems a little strange to me coming from a C# background, and that there are different ways to declare an array with static data.

Creating Arrays

For example, you can declare in a single line using semi-colons to separate the values, or use new lines to separate the values.  I prefer a single line to preserve space, but it really doesn’t matter.

 

You can even create an array with a loop, which is an interesting tool:

 

Another interesting approach is to create an Array with a specified length and initial default value.  This code below will create an array with 10 elements all set to the value of “value”.

 

Iterating through an Array

You can loop through an array like this using the for to loop:

 

The For in is even easier:

 

Another option is an Array iter, which uses a lambda type function that will be executed for each item in the array.  I think the for in loop is cleaner, but another option:

 

Filtering Arrays

Similar to a JQuery filter on an array, there is a F# equivalent, which is just like a Where clause for a lambda expression in C#.  You pass in a formula to evaluate for each item in the array, and if true will added to the filtered array, if not it doesn’t make the cut.

 

Sorting Arrays

Finally sorting arrays comes with two basic options, using the default sorting key, or specifying your own key to sort by, again the same as the lambda expression in C#.

 

 

Next week, I will go over the next step up from Arrays, Lists and Dictionaries.  How they’re similar to the similar types in C#, and how its slightly different.  Have a good week!

Leave a Reply

Your email address will not be published. Required fields are marked *