Swap elements in nested list

Hello, I am quite new to Elixir (I already start loving the language).
I am trying to write a function that swaps two elements in nested list.
For instance, I want to swap the third element at the first row with the fifth element at the third row I would write something like swap.(list, {0, 2}, {2, 4}).
My current version is

swap = fn
  list, {i1, j1}, {i2, j2} ->
    temp = list |> Enum.at(i1) |> Enum.at(j1)
    row1 = list |> Enum.at(i1)
    row2 = list |> Enum.at(i2)
    new_row1 = row1 |> List.replace_at(j1, Enum.at(row2, j2))
    new_row2 = row2 |> List.replace_at(j2, temp)
    list |> List.replace_at(i1, new_row1) |> List.replace_at(i2, new_row2)
list = [
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5]
swap.(list, {0, 2}, {2, 4})

I am wondering if there is better way of doing this.

Maybe get_in and put_in would be useful here.

@LostKobrakai: It’s not as easy as it looks, please see José Valim’s answer in similar topic.

In short:

  1. For simple example like here it’s totally ok to use get_in and update in functions, but …
  2. If this data is only example for bigger source then recommend way, but much more verbose is to map lists.
  3. Vectors should solve it, but I don’t know when they will be available (if any)

@baruh : How about look for a library? First that I found is Matix, but I don’t used/tested it, so I can’t say if it’s good and/or optimized enough.

I don’t think that a list of lists is a good way to do matrices in Elixir. I think you’re getter off by doing a Map like:

  {0, 0} => 1,
  {0, 1} => 2,

Swapping is then pretty easy, you just

val1 = Map.get(matrix, coords1)
val2 = Map.get(matrix, coords2)
%{matrix | coords1 => val2, coords2 => val1}

@LostKobrakai Thank you! I didn’t know for get_in and put_in.
@benwilson512 Thanks! I am thinking of switch to map at the end might be the easiest way.
@Eiji Thanks! I took a quick look at the library and it is taking similar to my approach. I will switch to implementation with map instead of a nested list, what @benwilson512 suggested. Another library that I found for linear algebra also uses nested lists.
I edited the reply to be one post. No need of spam.