Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap key and value in a map in fsharp

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!

like image 731
user3608127 Avatar asked Dec 06 '22 21:12

user3608127


2 Answers

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

like image 163
FoggyFinder Avatar answered Dec 31 '22 17:12

FoggyFinder


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.

like image 26
Dax Fohl Avatar answered Dec 31 '22 19:12

Dax Fohl