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?
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 this:
ToDictionary(id, fun v -> if v % 2 = 1 then "Odd" else "Even")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With