Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ToDictionary to work in F#?

Tags:

c#

linq

f#

I have this C# example, which will create a dictionary of odd and even numbers from an array of integers:

int[] values = new int[]
{
    1,
    2,
    3,
    5,
    7
};

Dictionary<int, string> dictionary = 
           values.ToDictionary(key => key, val => (val % 2 == 1) ? "Odd" : "Even");

// Display all keys and values.
foreach (KeyValuePair<int, string> pair in dictionary)
{
    Console.WriteLine(pair);
}

Output is:

[1, Odd]
[2, Even]
[3, Odd]
[5, Odd]
[7, Odd]

I want to do it similarly in F# using ToDictionary, and have this so far:

let values = [| 1; 2; 3; 5; 7 |]

let dictionary = values.ToDictionary( ??? )

// Display all keys and values.
for d in dictionary do
    printfn "%d %s" d.Key d.Value

But how will I write the logic inside ToDictionary?

like image 959
brinch Avatar asked Jun 25 '15 20:06

brinch


2 Answers

You can certainly use ToDictionary (and all other LINQ methods) from F#, but sometimes it is more idiomatic to use functions from the F# library.

If I vanted to create this dictionary, I'd use something like this:

let values = [| 1; 2; 3; 5; 7 |]
let dictionary = dict [ for v in values -> v, if v % 2 = 1 then "Odd" else "Even" ]

Here dict is an F# library function that creates a dictionary from tuples containing keys and values (the tuple is created using , and so we use v as the key and a string as a value).

like image 76
Tomas Petricek Avatar answered Oct 30 '22 10:10

Tomas Petricek


Like this:

ToDictionary(id, fun v -> if v % 2 = 1 then "Odd" else "Even")
like image 23
Daniel Avatar answered Oct 30 '22 10:10

Daniel