How to create a new map that is similar to the original one, but with swapped keys and values in Fsharp? For example, I have this
let map1 =
[("A", "1"); ("B", "2"); ("C", "3");]
|> Map.ofList
and want to get this:
let map2 =
[("1", "A"); ("2", "B"); ("3", "C");]
|> Map.ofList
Thank you for your help!
Perhaps you will approach this decision:
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"
Print:
map [("A", "1"); ("B", "2"); ("C", "3")]
map [("1", "A"); ("2", "B"); ("3", "C")]
Link: http://ideone.com/cfN2yH
You could convert it to a list and back, calling a function to swap 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 method somewhat highlights what's nice about functional programming--you can build up complex behavior just by combining small building blocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With