Search code examples
dictionaryf#functional-programmingswap

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!


Solution

  • 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