Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# collection initializer syntax

Tags:

inline

f#

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.

like image 999
srparish Avatar asked Mar 17 '11 15:03

srparish


3 Answers

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 |]
like image 57
Daniel Avatar answered Nov 09 '22 23:11

Daniel


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]
like image 42
kvb Avatar answered Nov 10 '22 01:11

kvb


I don't believe F# has an explicit collection initializer syntax. However it's usually very easy to initialize F# collections. For example

let map = [ ("One", 1); ("Two", 2) ] |> Map.ofSeq

Getting to BCL collections is usually a bit more difficult because they don't always have the handy conversion functions. Dictionary<TKey, TValue> works though because you can use the LINQ method

let map = 
  let list = [ ("One", 1); ("Two", 2) ] 
  System.Linq.Enumerable.ToDictionary(list, fst, snd)
like image 14
JaredPar Avatar answered Nov 10 '22 01:11

JaredPar