citxx
citxx

Reputation: 2545

Extend one list of key-value pairs with another one

I have two lists of key-value pairs ([{key_1, value_1}, ..., {key_n, value_n}]). What is the best method of updating first list with the second one? For example:

1> extend([{1, "one"}, {2, "too"}], [{2, "two"}, {3, "three"}]).
[{1, "one"}, {2, "two"}, {3, "three"}]

I've found just two similar function: lists:keystore/4, which updates a single tuple, and lists:keymerge, which merges two lists without removing key duplicates.

Upvotes: 1

Views: 479

Answers (2)

Odobenus Rosmarus
Odobenus Rosmarus

Reputation: 5998

for instance

extend(L1,L2) -> 
    lists:foldl(fun({K,V},Acc) -> lists:keystore(K,1,Acc,{K,V}) end, L1,L2).

or

extend(L1,L2) ->
    compact(lists:keysort(1,L1++L2),[]).

compact([],Acc) -> lists:reverse(Acc);
compact([{K,_},{K,V}| Rest], Acc) -> compact([{K,V} |Rest],Acc);
compact([X|Rest],Acc) -> compact(Rest,[X|Acc]).

Upvotes: 0

citxx
citxx

Reputation: 2545

I've found the answer myself. Erlang's orddict module deals with pure sorted list of {key, value} pairs. So, extend function can be defined as follows:

extend(L1, L2) ->
    orddict:merge(fun(_Key, _V1, V2) -> V2 end, L1, L2).

If L1 and L2 aren't initially sorted, then they can be transformed to orddicts with orddict:from_list/1.

Upvotes: 2

Related Questions