Reputation: 2765
A funky title perhaps, but I'm having a problem with the following:
Given a list of type (a * b) list
, I want to create a new list with type (a * b list) list
. An example:
Given list let testList = [(1,"c");(2,"a");(1,"b")]
, my function should return [(1, ["c";"b"]; (2, ["a"])]
.
I have the following, but I'm a little stuck on how to continue:
let rec toRel xs =
match xs with
| (a,b)::rest -> (a,[b])::toRel rest
| _ -> []
Upvotes: 2
Views: 79
Reputation: 26204
You can use the built-in function List.groupBy
and then map to remove the redundant key:
testList |> List.groupBy fst |> List.map (fun (k,v) -> (k, List.map snd v))
// val it : (int * string list) list = [(1, ["c"; "b"]); (2, ["a"])]
Otherwise if you want to continue with a match you can do something like this:
let toRel x =
let rec loop acc xs =
match xs with
| (k, b) :: rest ->
let acc =
match Map.tryFind k acc with
| Some v -> Map.add k (b::v) acc
| None -> Map.add k [b] acc
loop acc rest
| _ -> acc
loop Map.empty x |> Map.toList
Or using Option.toList
you can write it:
let toRel x =
let rec loop acc xs =
match xs with
| (k, b) :: rest ->
let acc =
let lst = Map.tryFind k acc |> Option.toList |> List.concat
Map.add k (b::lst) acc
loop acc rest
| _ -> acc
loop Map.empty x |> Map.toList
Upvotes: 8