> Erlang中文手册 > keyreplace/4 替换元组列表里的值

lists:keyreplace/4

替换元组列表里的值

用法:

keyreplace(Key, N, TupleList1, NewTuple) -> TupleList2

内部实现:

-spec keyreplace(Key, N, TupleList1, NewTuple) -> TupleList2 when
      Key :: term(),
      N :: pos_integer(),
      TupleList1 :: [Tuple],
      TupleList2 :: [Tuple],
      NewTuple :: Tuple,
      Tuple :: tuple().

keyreplace(K, N, L, New) when is_integer(N), N > 0, is_tuple(New) ->
    keyreplace3(K, N, L, New).

keyreplace3(Key, Pos, [Tup|Tail], New) when element(Pos, Tup) == Key ->
    [New|Tail];
keyreplace3(Key, Pos, [H|T], New) ->
    [H|keyreplace3(Key, Pos, T, New)];
keyreplace3(_, _, [], _) -> [].

从元组列表 TupleList1 里查找元组的第 N 个值跟 Key 是一样的元素,如果找到则用新元组替换,并返回一个新的元组列表 TupleList1,找不到则返回原来的元组列表 TupleList1

TupleList = [{a, 1}, {b, 2}, {c, 3}, {d, 4}],
lists:keyreplace(b, 1, TupleList, {b, 22}).