[英]Compose immutable F# map of list of strings
在C#中,我可以很容易地構建一個Dictionary<string, List<string>>
。 如果我正在閱讀大型項目數據庫,我可以執行以下操作:
var dict = new Dictionary<string, List<string>>();
foreach(string[] row in data)
if (!dict.ContainsKey(row[0]))
dict.add(row[0], new List<string>() { row };
else
dict[row[0]].add(row);
現在的問題是,如何在f#中使用不可變的Map<string, string list>
?
data
|> Seq.groupBy (fun row -> row.[0])
|> Map.ofSeq
這是一個更詳細的解決方案,與您的C#示例非常相似:
data |> Seq.fold (fun map row ->
match Map.tryFind row.[0] map with
| Some rows -> Map.add row.[0] (row::rows) map
| None -> Map.add row.[0] [row] map) Map.empty
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.