操作Fsharp列表

时间:2013-02-23 19:44:57

标签: list filter f# variable-length

好的,所以我过去几天一直在玩F#,发现一些教程在网上开球(没有解决方案!)如果我有以下列表 -

let new = [
 (1808,"RS");
 (1974,"UE");
 (1066,"UE");
 (3005,"RS");
 (2007,"UE");
 (2012,"UE");
 ]

如何过滤此列表以首先显示RS组中的项目数,其次是UE? 我在想List.filter,List.length,不太清楚从这两个去哪里获得每个组的具体数字。谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

通常,Seq.groupBy可以轻松处理分组操作。

如果您只想计算每组中的项目数,Seq.countBy就可以了。

[ (1808,"RS");
  (1974,"UE");
  (1066,"UE");
  (3005,"RS");
  (2007,"UE");
  (2012,"UE"); ]
// 'countBy' returns a sequence of pairs denoting unique keys and their numbers of occurrences
// 'snd' means that we try to pick a key as the *second* element in each tuple
|> Seq.countBy snd
// convert results back to an F# list
|> Seq.toList

// val it : (string * int) list = [("RS", 2); ("UE", 4)]