简体   繁体   English

列表/序列中的F#词典生成器

[英]F# Dictionary Builder from List/Seq

Is there a constructor for Dictionary in F# (that takes a Seq/List as input, and output a Dictionary)? F#中是否有Dictionary的构造函数(将Seq / List作为输入,然后输出Dictionary)? I have written the following code that does what I want, but I am just curious maybe it is already implemented (and so I don't need to implement it myself) 我已经编写了下面的代码来实现我想要的功能,但是我很好奇,也许它已经实现了(所以我不需要自己实现它)

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

I know that in C#, you can use .ToDictionary (using System.Linq) 我知道在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"}

Thank you very much. 非常感谢你。

The signature of the dict function it's as follows: dict函数的签名如下:

dict : seq<'Key * 'Value> -> IDictionary<'Key,'Value> 

So it takes a key value sequence as input. 因此,它将键值序列作为输入。 The key here would be to give it a key value sequence. 这里的关键是给它一个键值序列。 In your case, you could use map instead of iter. 在您的情况下,可以使用map而不是iter。 The lines of code will be similar but it's a more functional way. 代码行将相似,但这是一种更实用的方法。

aList 
|> Seq.map (fun a -> keyFunc a, valueFunc a )
|> dict

Edit 编辑

As TheQuickBrownFox have noted in the comments, the dict function produces a read-only dictionary. 正如TheQuickBrownFox在注释中指出的那样,dict函数生成一个只读字典。

I would recommend that you just use LINQ: 我建议您只使用LINQ:

open System.Linq
[1; 2; 3].ToDictionary(id, (*) 2)

Either use it directly or use it in your helper function if you'd rather use a function than an extension method. 如果要使用功能而不是扩展方法,则可以直接使用它,也可以在辅助函数中使用它。

module Seq =
    open System.Linq
    let toDictionary (f:'s -> 'k) (g:'s -> 'v) (xs:_ seq) = xs.ToDictionary(f, g)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM