来自列表/序列的 F# 字典生成器

CH *_*Ben 5 f# dictionary

F# 中是否有字典的构造函数(以 Seq/List 作为输入,并输出字典)?我编写了以下代码来实现我想要的功能,但我只是好奇它是否已经实现(所以我不需要自己实现它)

let DictionaryBuilder (keyFunc:'a->'b) (valueFunc:'a->'c) aList =
    let dict = new Dictionary<'b,'c>()
    aList 
    |> Seq.iter (fun a -> dict.Add(keyFunc a, valueFunc a ))
    dict    // return
Run Code Online (Sandbox Code Playgroud)

我知道在 C# 中,您可以使用 .ToDictionary (使用 System.Linq)

// using System.Collections.Generic;
// using System.Linq;
List<string> example = new List<string> {"a","b","c"};
Dictionary<string,string> output = example.ToDictionary(x => x+"Key", x => x+"Value");
// Output: {"aKey": "aValue", "bKey": "bValue", "cKey": "cValue"}
Run Code Online (Sandbox Code Playgroud)

非常感谢。

Asi*_*aga 4

dict函数的签名如下:

dict : seq<'Key * 'Value> -> IDictionary<'Key,'Value> 
Run Code Online (Sandbox Code Playgroud)

所以它需要一个键值序列作为输入。这里的关键是给它一个键值序列。在你的情况下,你可以使用map而不是iter。代码行将相似,但这是一种更实用的方式。

aList 
|> Seq.map (fun a -> keyFunc a, valueFunc a )
|> dict
Run Code Online (Sandbox Code Playgroud)

编辑

正如 TheQuickBrownFox 在评论中指出的那样, dict 函数生成一个只读字典。

  • 请注意“dict”会生成只读字典(当您尝试添加或删除项目时,它会抛出异常)。您可以通过再次将该字典传递给 Dictionary 构造函数来解决此问题: `... |&gt; dict |&gt; System.Collections.Generic.Dictionary` (3认同)