使用列表时,所有元素通常具有相似的数据类型或含义。您很少看到像 ["John Doe","1970-01-01","London"] 这样的列表,而是 #person{name="John Doe",...} 甚至 {"John Doe",...}。要更改记录和元组中的值:
-record(person,{name,born,city}).
f(#person{}=P) -> P#person{city="New City"}. % record
f({_,_,_,}=Tuple) -> erlang:setelement(3,Tuple,"New City"). % tuple
这可能无法解决您的特定问题。以您自己的评论为例:
f1([H1,H2,_H3,H4,H5],E) -> [H1,H2,E,H4,H5].
如果您对环境和问题给出更具体的描述,则更容易确定哪种解决方案可能最有效。
编辑:一个(相当糟糕的)解决方案 1。
replacenth(L,Index,NewValue) ->
{L1,[_|L2]} = lists:split(Index-1,L),
L1++[NewValue|L2].
1> replacenth([1,2,3,4,5],3,foo).
[1,2,foo,4,5]
或者根据列表的长度稍微提高效率。
replacenth(Index,Value,List) ->
replacenth(Index-1,Value,List,[],0).
replacenth(ReplaceIndex,Value,[_|List],Acc,ReplaceIndex) ->
lists:reverse(Acc)++[Value|List];
replacenth(ReplaceIndex,Value,[V|List],Acc,Index) ->
replacenth(ReplaceIndex,Value,List,[V|Acc],Index+1).
上面的函数 f1 更好,但也许问题仍然存在,如上所述或here。