I came up with this simple algorithm (converts a list of tuples into a collection of keys for keys to lists) that I need in F # code:
let MergeIntoMap<'K,'V when 'K: comparison>(from: seq<'K*'V>): Map<'K,seq<'V>>= let keys = from.Select(fun (k,v) -> k) let keyValuePairs = seq { for key in keys do let valsForKey = from.Where(fun (k,v) -> key = k).Select(fun (k,v) -> v) |> seq yield key,valsForKey } keyValuePairs |> Map.ofSeq
Input Example:
[ ("a", 1); ("b", 2), ("a", 3) ]
Output:
dict [ ("a", [1; 3]), ("b", [2]) ]
And I thought it should be something that already exists in BCL or F #, consisting of high-order functions? If so, can someone contact me? Because I'm sure my code is not very efficient as it is ...
source share