DetailPage-MSS-KB

Microsoft small business knowledge base

Article ID: 2844310 - Last Review: May 7, 2013 - Revision: 2.0

About Author:

Collapse this tableExpand this table
Collapse this imageExpand this image
This article is provided by MVP Eriawan Kusumawardhono (http://mvp.microsoft.com/en-us/mvp/Eriawan%20Kusumawardhono-4040024) . Microsoft is so thankful that MVPs who proactively share their professional experience with other users. The article would be posted on MVP's website (http://mvp.microsoft.com/en-us/mvp/Eriawan%20Kusumawardhono-4040024) or blog (http://mugi.or.id/blogs/eriawan) later.

On This Page

Overview of collections in F#

Collections in F# is not different from .NET collections. But in F#, by default the collections has this behavior concerning the nature of functional programming languages:
  • They are immutable (unless Array)
  • Support lazy evaluations (except Array, because of its fixed size nature)
But in F#, the collections are not just list and IEnumerable (just like the ones in .NET Base Class Libraries (.NET BCL).

Currently in F# 3.0, the collections are:
  1. Sequence. It is used to represent sequence of elements. The order of the elements are not important. Sequence is most effective to use when not all of the elements are not used.
  2. List. It is the same list in .NET BCL List.
  3. Array. Mutable collection. It has fixed size, with zero based indexes and all of the elements has to have the same type.
  4. Map. Immutable dictionary of elements.
  5. Set. An immutable set that's based on binary trees, where comparison is the F# structural comparison function, which potentially uses implementations of the IComparable interface on key values. The set in F# has the same concept of set in mathematics especially relational algebra.
Note: this article could be used as complementary information on F# collections in MSDN Library, not replacing it.

Sequences

Sequence in F# is basically the same as IEnumerable in .NET BCL. Therefore, any .NET type that implements IEnumerable is a sequence.

Enumerating sequence is computed when needed, and it's evaluated later therefore it is also lazily evaluated. This evaluation strategy is often called lazy evaluation, and it is therefore effective for the case of not evaluating all of the sequence elements.

Sequence operations are in Seq module in F#. The operation of map, filter, and many more has the same result as in LINQ. But sequence has more operations such as fold, unfold, and many more.

Sequence can be expressed as sequence expressions. For example, to express sequence that has number ranges:

        // normal sequence
        let seq1 = seq { 1 .. 100 }
      
It can contain stepping increments. For example:

        // sequence with stepping
        let seq2 = seq { 0 .. 10 .. 100 }
      
The seq2 will contain 0, 10, 20, 30 to 100 respectively.

Because of the nature of lazy evaluation and not all of the elements are evaluated, sequence can contain infinite number of elements.

Note: this feature of infinite number of elements are not available in .NET BCL and also in C#/Visual Basic. Also doing interoperability while operating with infinite sequence in F# could have undesired result on C#/Visual Basic.

For example (from MSDN Library):

        let seqInfinite = Seq.initInfinite (fun index ->
        let n = float( index + 1 )
        1.0 / (n * n * (if ((index + 1) % 2 = 0) then 1.0 else -1.0)))
        printfn "%A" seqInfinite
      
Sequence operations are available in Seq module in F# Core Library.


List

List is an immutable collection of elements and it is ordered. The term ordered means the elements in the collection is indexed, not sorted.

To create a list, the syntax is different from creating sequence. The elements are enclosed by "[ ]".

Example of creating syntax:

let list123 = [ 1; 2; 3 ]
There is also alternative syntax by separating the elements with line break, for example:

        let list123 = [
        1
        2
        3 ]
      
Because List is also ordered, therefore there are other interesting features of List in F# to use as well.

Lists can be concatenated as long as the types are the same by using the "@" operator, for example:

let list3 = list1 @ list2
You can attach elements to a list using :: (cons) operator. Again, the elements type has to be the same.

For example:

let list2 = 100 :: list1
These are the properties of List:

Collapse this imageExpand this image
List properties
([anySimpleType])

List in F# can be used and accessed using List properties of Head and Tail, in the form of pattern matching.

For example below, the code will recursively sum the head with the rest of the elements:

        let sum list =
        let rec loop list acc =
        match list with
        | head :: tail -> loop tail (acc + head)
        | [] -> acc
        loop list 0
      

This head and tail pattern matching is very useful to examine a list not just recursively, but it can be iterated with index using List.iteri function built in F#.

List is available on List module in F# core library.

Array

According to MSDN Library, F# array is:

"Arrays are fixed-size, zero-based, mutable collections of consecutive data elements that are all of the same type."

One other thing is, all elements in an array has indexes, therefore they are ordered.

To create an array, the elements are enclosed in "[| |]" symbols.

This is the sample to create new array:

let array1 = [| 1; 2; 3 |]
And we can also use the line break as separator like List, for example:

        let array1 =
        [|
        1
        2
        3
        |]
      
Array is available on Array module in F# Core library.

Set and Map

Set and Map are unordered collections. This means the elements do not preserve the order of the collections as they can be changed by any operations on Set and Map.

Set is a collection of elements with the same type, just like Seq, List, and Array. Set can be constructed by using existing elements of sequence, list or array.

For example, constructing Set from Sequence:

let b = Set.ofSeq [ 5 .. 15 ]
Symbol b will contain a set elements with values of 5 to 15.

There are other functions that perform features unique to Set such Set.difference, Set.compare, Set.add, Set.intersect, Set.isSubset just like Set operations on math.

Map is just like Dictionary on .NET BCL, a collections of value pair of Key-Value. The Key must be unique, but the value does not have to be unique.

Initializing Map is quite similar with creating Dictionary. For example: (taken from F# Wikibooks)

        let holidays =
        Map.empty.
        Add("Christmas", "Dec. 25").
        Add("Halloween", "Oct. 31").
        Add("Darwin Day", "Feb. 12").
        Add("World Vegan Day", "Nov. 1");; (* Start with empty Map *)
      
Set and Map are available in Set module and Map module in F# Core Library.

More information

This is the official page of F# Collection on MSDN Library: http://msdn.microsoft.com/en-us/library/hh967652.aspx (http://msdn.microsoft.com/en-us/library/hh967652.aspx)

This is a community Wikibooks page of F# Set and Map explanation: http://en.wikibooks.org/wiki/F_Sharp_Programming/Sets_and_Maps (http://en.wikibooks.org/wiki/F_Sharp_Programming/Sets_and_Maps)

Community Solutions Content Disclaimer

MICROSOFT CORPORATION AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY, RELIABILITY, OR ACCURACY OF THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN. ALL SUCH INFORMATION AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION AND RELATED GRAPHICS, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, TITLE AND NON-INFRINGEMENT. YOU SPECIFICALLY AGREE THAT IN NO EVENT SHALL MICROSOFT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF USE, DATA OR PROFITS, ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OR INABILITY TO USE THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN, WHETHER BASED ON CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE, EVEN IF MICROSOFT OR ANY OF ITS SUPPLIERS HAS BEEN ADVISED OF THE POSSIBILITY OF DAMAGES.

Applies to
  • Microsoft Visual Studio Express 2012 for Web
  • Microsoft Visual Studio Premium 2012
  • Microsoft Visual Studio Professional 2012
  • Microsoft Visual Studio Test Professional 2012
  • Microsoft Visual Studio Ultimate 2012
  • Microsoft Visual Studio 2010 Premium
  • Microsoft Visual Studio 2010 Professional
  • Microsoft Visual Studio 2010 Ultimate
Keywords: 
kbstepbystep kbmvp kbcommunity KB2844310
Share
Additional support options
Ask The Microsoft Small Business Support Community
Contact Microsoft Small Business Support
Find Microsoft Small Business Support Certified Partner
Find a Microsoft Store For In-Person Small Business Support