lists:keymap/3
元组列表里元组的值被函数调用
用法:
keymap(Fun, N, TupleList1) -> TupleList2
内部实现:
-spec keymap(Fun, N, TupleList1) -> TupleList2 when
Fun :: fun((Term1 :: term()) -> Term2 :: term()),
N :: pos_integer(),
TupleList1 :: [Tuple],
TupleList2 :: [Tuple],
Tuple :: tuple().
keymap(Fun, Index, [Tup|Tail]) ->
[setelement(Index, Tup, Fun(element(Index, Tup)))|keymap(Fun, Index, Tail)];
keymap(Fun, Index, []) when is_integer(Index), Index >= 1,
is_function(Fun, 1) -> [].
元组列表 TupleList1 里每个元组的第 N 个值被函数 Fun 调用,调用产生的新值替换原来的,最后返回被函数 Fun 遍历调用过的新列表 TupleList2
TupleList = [{a, 1}, {b, 2}, {c, 3}, {d, 4}],
lists:keymap(fun(X) -> X * 2 end, 2, TupleList).