Difference between put_elem and insert_at?

What is the difference between Kernel.put_elem and Tuple.insert_at?

Kernel.put_elem() replaces whereas Tuple.insert_at() adds.

iex> put_elem({:foo}, 0, :bar)
{:bar}
iex> Tuple.insert_at({:foo}, 0, :bar)
{:bar, :foo}

Implementations:

# lib/elixir/lib/kernel.ex
@spec put_elem(tuple, non_neg_integer, term) :: tuple
def put_elem(tuple, index, value) do
  :erlang.setelement(index + 1, tuple, value)
end

# lib/elixir/lib/tuple.ex
@spec insert_at(tuple, non_neg_integer, term) :: tuple
def insert_at(tuple, index, value) do
  :erlang.insert_element(index + 1, tuple, value)
end
5 Likes