Domanda

Ok so i've been playing around with F# the last few days and found some tutorials kicking around online (no solutions!) If i had the following list-

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

How would I filter this list to show first the number of items in group RS, and secondly UE? I'm thinking List.filter, List.length, not too sure where to go from these two to get specific numbers for each group. Thanks for any help

È stato utile?

Soluzione

In general, grouping operations are easily handled by Seq.groupBy.

If you only want to count number of items in each group, Seq.countBy is the way to go.

[ (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)]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top