Key and value exchange on a map in fsharp
How can I create a new map similar to the original, but with changed keys and values ββin Fsharp? For example, I have this
let map1 =
[("A", "1"); ("B", "2"); ("C", "3");]
|> Map.ofList
and want the following:
let map2 =
[("1", "A"); ("2", "B"); ("3", "C");]
|> Map.ofList
Thanks for your help!
+3
source to share
2 answers
Perhaps you will accept this solution:
let map1 = Map.ofList [("A", "1"); ("B", "2"); ("C", "3")]
map1 |> printfn "%A"
let rev map: Map<string,string> =
Map.fold (fun m key value -> m.Add(value,key)) Map.empty map
rev map1 |> printfn "%A"
Printing
map [("A", "1"); ("B", "2"); ("C", "3")]
map [("1", "A"); ("2", "B"); ("3", "C")]
Link: http://ideone.com/cfN2yH
+6
source to share
You can convert it to and from a list by calling the exchange function in the middle.
let swap (x, y) = y, x
let swapAll tuples = List.map swap tuples
let invert map = map |> Map.toList |> swapAll |> Map.ofList
This technique emphasizes somewhat, which is nice in functional programming - you can create complex behaviors simply by concatenating small building blocks.
+3
source to share