2013-02-23 69 views
-3

好了,所以我一直在F#玩弄的最後幾天,發現了一些在線教程踢左右(無解!)如果我有以下列表 -操縱的Fsharp列表

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

我會怎樣過濾此列表以首先顯示組RS中的項目數量,其次是UE? 我在想List.filter,List.length,不太清楚從這兩個地方去哪裏去得到每個組的具體數字。感謝您的幫助

回答

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)] 
+0

你可以向我解釋一下,通過snd和Seq.toList的函數Seq.count實質上是指通俗的說法嗎? – user2093122 2013-02-23 20:00:03

+0

我給代碼片段添加了註釋。您可以按照我的答案中的鏈接瞭解這些操作。 – pad 2013-02-23 20:05:54

+0

歡呼的隊友非常感謝 – user2093122 2013-02-23 22:10:25