Question

If i have a 2D array such as

test = array2D [|[|1; 2; 3|];
                 [|4; 5; 6|];]

and I want to swap two elements by there index so for example

swap test (0,0) (1,1) //[|[|5; 2; 3|];
                        //[|4; 1; 6|];]

How would I write that? I have seen solutions that pass each item by reference and mutates it, but that seems unidiomatic to me (I could be wrong).

Was it helpful?

Solution

You can write a swap function using Array2D.mapi that doesn't mutate the original array. This will return a new array with the swapped values:

let swap (arr : int[,]) i1 i2 =
    let map i j v =
        match (i,j) with
        | t when t = i1 -> arr.[fst i2, snd i2]
        | u when u = i2 -> arr.[fst i1, snd i1]
        | _ -> v
    arr |> Array2D.mapi map

OTHER TIPS

Here is a simple in-place swap.

module Array2D =
    let swap (x1, y1) (x2, y2) (array: _[,]) =
        let temp = array.[x1, y1]
        array.[x1, y1] <- array.[x2, y2]
        array.[x2, y2] <- temp
        array

If you want a copy, just insert a call to Array2D.copy:

array2D [|[|1; 2; 3|];[|4; 5; 6|]|]
|> Array2D.copy
|> Array2D.swap (0,0) (1,1) 
|> printfn "%A"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top