F# collection initializer syntax

srparish picture srparish · Mar 17, 2011 · Viewed 10.8k times · Source

What is the collection initializer syntax in F#? In C# you can write something like:

new Dictionary<string, int>() {
    {"One", 1},
    {"two", 2}}

How do I do the same thing in F#? I suppose i could roll my own syntax, but seems like there should be a built-in or standard one already.

Answer

Daniel picture Daniel · Mar 17, 2011

To elaborate a bit on collection initialization in F#, here are a few examples:

read-only dictionary

dict [ (1, "a"); (2, "b"); (3, "c") ]

seq (IEnumerable<T>)

seq { 0 .. 99 }

list

[1; 2; 3; 4; 5]

set

set [1; 2; 3; 4; 5]

array

[| 1; 2; 3; 4; 5 |]