Replace an element at an index in a list in Erlang

柔情痞子 提交于 2020-03-21 20:12:29

问题


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]]).

回答1:


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.



来源:https://stackoverflow.com/questions/4370756/replace-an-element-at-an-index-in-a-list-in-erlang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!