How to get ToDictionary to work in F #?

I have this C # example that 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:

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

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

 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 do I write the logic inside a ToDictionary?

+6
source share
2 answers

Like this:

 ToDictionary(id, fun v -> if v % 2 = 1 then "Odd" else "Even") 
+4
source

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

If I wanted to create this dictionary, I would 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 ​​(a tuple is created with,, and therefore we use v as a key and a string as a value).

+11
source

Source: https://habr.com/ru/post/989770/


All Articles