lists:sort 排序規則:先排長度,再排內容
34> A = [{a,1},{c,2},{d,3},{a,1}].
[{a,1},{c,2},{d,3},{a,1}]
35> lists:sort(A).
[{a,1},{a,1},{c,2},{d,3}]
36> B = [{a,1,2},{b,2},{d,4},{c,5},{a,1,1},{a},{c,3}].
[{a,1,2},{b,2},{d,4},{c,5},{a,1,1},{a},{c,3}]
37> lists:sort(B).
[{a},{b,2},{c,3},{c,5},{d,4},{a,1,1},{a,1,2}]
38>
%% ----------------------------------------------------
%% Func: merge/1 (KeyList)
%% Description: 合併同類元組列表
%% Args: KeyList::list({type,num}|{type,num})
%% Returns: list({type,num}|{type,num})
%% Example: merge([{a,1},{c,2},{d,3},{a,1}]) -> [{a,2},{c,2},{d,3}]
%% ----------------------------------------------------
merge(List) ->
List2 = lists:sort(List),%%排序後才能 纔能讓相鄰的相同的Type進行匹配
merge(List2,[]).
merge( [{Type,A}|T1],[{Type,B}|T2]) -> merge(T1,[{Type,A+B}|T2]);%%亂序下不會匹配上這一行
merge([H|T],List2) -> merge(T,[H|List2]);
merge([],List2) -> lists:reverse(List2).
26> t:merge([{a,1},{c,2},{d,3},{a,1}]).
[{a,2},{c,2},{d,3}]