> Erlang中文手册 > keystore/4 在元组列表里存储一个值

lists:keystore/4

在元组列表里存储一个值

用法:

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

内部实现:

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

keystore(K, N, L, New) when is_integer(N), N > 0, is_tuple(New) ->
    keystore2(K, N, L, New).

keystore2(Key, N, [H|T], New) when element(N, H) == Key ->
    [New|T];
keystore2(Key, N, [H|T], New) ->
    [H|keystore2(Key, N, T, New)];
keystore2(_Key, _N, [], New) ->
    [New].

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

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