Proposal: Allow neg_integer_index in Tuple.insert_at and Tuple.delete_at

13 views
Skip to first unread message

Kensei N

unread,
Feb 8, 2020, 8:11:45 AM2/8/20
to elixir-lang-core
Hi !

I propose modifing Tuple.insert_at/3 and Tuple.delete_at/2 to allow neg_integer index, like Enum.at/3

Specifically, I would like to fix as below. (and delete insert_at and delete_at from elixir_rewrite.erl)

@spec insert_at(tuple, integer, term) :: tuple
  def insert_at(tuple, index, value) do
    non_neg_index =
      if index >= 0 do
        index
      else
        count = tuple_size(tuple)
        index + count + 1
      end

    :erlang.insert_element(non_neg_index + 1, tuple, value)
  end

@spec delete_at(tuple, integer) :: tuple
 def delete_at(tuple, index) do
    non_neg_index =
      if index >= 0 do
        index
      else
        count = tuple_size(tuple)
        index + count
      end

    :erlang.delete_element(non_neg_index + 1, tuple)
  end


José Valim

unread,
Feb 8, 2020, 9:27:40 AM2/8/20
to elixir-l...@googlegroups.com
Hi Kensei!

So the reason we don’t allow negative indexes for tulles is because we would have to support them on elem/2 but if we do so it can’t work on guards (at least not efficiently).

Also, as the docs for Tuple says, you should really really avoid index access for tuples. Pattern matching is almost always better.

Thanks!
Reply all
Reply to author
Forward
0 new messages