我有这个C#示例,它将从整数数组创建奇数和偶数的字典:
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中编写逻辑?
解决方法
像这样:
ToDictionary(id,fun v -> if v % 2 = 1 then "Odd" else "Even")