替换Erlang列表中索引的元素 [英] Replace an element at an index in a list in Erlang

查看:321
本文介绍了替换Erlang列表中索引的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,需要定期更新其元素。元素没有列表的键:keyreplace。它也将动态增长。这是更新列表中特定索引的元素的好方法吗?有没有更好的算法?

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


推荐答案

我不会建议以这种方式使用列表,这让我觉得你的问题可能与设计相关,而不是整齐地解决问题。也许如果你解释你有什么列表?

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.

我建议使用ets表或dict进行随机访问操作。

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

这篇关于替换Erlang列表中索引的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆