Search code examples
f#inline

F# collection initializer syntax


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.


Solution

  • As Jared says, there is no built-in support for this for arbitrary collections. However, the C# code is just syntactic sugar for Add method calls, so you could translate it to:

    let coll = MyCollectionType()
    ["One", 1; "Two", 2] |> Seq.iter coll.Add
    

    If you want to get fancy, you could create an inline definition to streamline this even further:

    let inline initCollection s =
      let coll = new ^t()
      Seq.iter (fun (k,v) -> (^t : (member Add : 'a * 'b -> unit) coll, k, v)) s
      coll
    
    let d:System.Collections.Generic.Dictionary<_,_> = initCollection ["One",1; "Two",2]