4

I have a list that will need its elements updated periodically. The elements do not have a key for lists:keyreplace. It will also grow dynamically. Is this a good way to update an element at a specific index in a list? Is there a better algorithm?

List = [1,2,3,4],
Index = 3,
NewElement = 5,
{HeadList, [_|TailList]} = lists:split(Index-1, List),
[1,2,5,4] = lists:append([HeadList, [NewElement|TailList]]).
MatthewToday
  • 269
  • 5
  • 10

1 Answers1

6

I wouldn't recommend using a list in this way, it makes me think that your problem might be design related rather than related to solving it neatly. Perhaps if you explains what you have the list for?

However if that is what you actually need/want/have to do; then what you are doing is correct.

I would recommend using an ets table or dict for random access operations.

Mazen Harake
  • 1,706
  • 1
  • 11
  • 17
  • I've though a bit about how I'm using the list, and yes you're correct. My random-access requirement is the most important requirement - the others: accessing the last element entered (actually the head of the list) at any time and traversal of the list from 1st entered to last entered, can easily be changed to use an etc/dict. I believe the solution will be to make a {Key, ListElem} tuple. Thanks for your insight! – MatthewToday Dec 06 '10 at 23:03