How to reset a segment of a list in Elixir?

In ruby I can do this:

vec1[a1...a2] = vec2[b1...b2]

That is to reset vec1 elements from a1 to a2 with the elements present in vec2 from b1 to b2.

What would be the best way to accomplish this in Elixir ?

Given immutability, you can’t.

However with lists you can generate a new value (list).

iex(1)> a = 0..10
0..10
iex(2)> b = 100..110
100..110
iex(3)> c = Enum.take(a,4) ++ (b |> Enum.drop(5) |> Enum.take(4)) ++ Enum.drop(a,8)
[0, 1, 2, 3, 105, 106, 107, 108, 8, 9, 10]
iex(4)> d = Enum.slice(a,0,4) ++ Enum.slice(b,5,4) ++ Enum.slice(a,8,3)
[0, 1, 2, 3, 105, 106, 107, 108, 8, 9, 10]
iex(5)>

Enum.drop/2
Enum.take/2
Enum.slice/3
Enum.slice/2

3 Likes

Yeah, this really suggests an algorithm not designed with immutability in mind. That being said, another approach is to think about what you want to keep, rather than what you want to replace and then put them together in the desired order.

Enum.concat([
  Enum.slice(vec1, 0, a1),
  Enum.slice(vec2, b1, b2 - b1),
  Enum.slice(vec1, -a2)
])
4 Likes

Yeah I think is the closest we can get to this in least amount of code