我有這樣的C#示例,這將創建奇數和偶數號碼的字典從整數數組:如何讓ToDictionary在F#中工作?
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);
}
輸出是:
[1, Odd]
[2, Even]
[3, Odd]
[5, Odd]
[7, Odd]
欲使用同樣做到這一點在F# ToDictionary,並且有這個至今:
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
但我會怎麼寫裏面ToDictionary邏輯?
@Jim Garrison:我嘗試了丹尼爾的回答,它工作。 – brinch