1 % ****************************************************************************** 2 % ------------------------------------------------------------------------------ 3 % 习题 5 4 % 合并列表,A=[{a,1},{b,2},{c,3},{b,1}],B=[{b,4},{c,5},{d,6},{d,2}]. 5 % 结果:[{a,1},{b,7},{c,8},{d,8}] 6 % D=[{a,3},{f,14},{k,39},{f,22},{g,88},{d,23}]. 7 % 把B列表合并到A列表,新增的放后面,不能用++ 8 % ------------------------------------------------------------------------------ 9 10 11 test5( A, B ) -> 12 M = test5a_2( A,[] ), 13 test5a_2( B, M ). 14 15 test5a_1( E, [Th|T], F, R ) -> 16 {Flag,V} = match(E ,Th), 17 test5a_1( E, T, Flag or F, [V|R] ); 18 test5a_1( E, [], F, R ) -> 19 case F of 20 true -> 21 R; 22 false -> 23 [E|R] 24 end. 25 26 test5a_2( [Th|T], R ) -> 27 M = test5a_1( Th, R, false, [] ), 28 Mr= lists:reverse(M), 29 test5a_2( T, Mr ) ; 30 test5a_2( [], R ) -> 31 R. 32 33 34 % 匹配成功,返回处理后的值,失败返回匹配B值 35 match( {Nam,ValA}, {Nam,ValB} ) -> 36 { true, {Nam,ValA+ValB} } ; 37 match( _, Th ) -> 38 { false, Th }.