F#: Reduce a list of tuples by grouping one of the elements into arrays

与世无争的帅哥 提交于 2019-12-25 02:29:06

问题


I have a list of tuples which i want to group by one of its elements as a key. For example, if i had this list of tuples:

[(A, "hello"), (A, "stack"), (A,"over"), (A, "flow"), (B, "how"), (B, "you"), (C, "doin")]

I would like to get a result in the form:

[(A, ["hello", "stack", "over", "flow"]), (B, ["how", "you"]), (C, ["doin"])]

I am new to F# so I am all out of ideas on how to do this. I thank you in advance.

cheers


回答1:


I think you are using incorrect delimiter for list elements - instead of , you need to use ;.

To get results use this snippet:

[("A", "hello"); ("A", "stack"); ("A","over"); ("A", "flow"); ("B", "how"); ("B", "you"); ("C", "doin")]
  |> Seq.groupBy fst 
  |> Seq.map (fun (key,groupping) -> key, (groupping |> Seq.map snd |> Seq.toList)) 
  |> Seq.toList


来源:https://stackoverflow.com/questions/25395075/f-reduce-a-list-of-tuples-by-grouping-one-of-the-elements-into-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!