前段时间我写了一些代码来合并两条记录。不是完全动态的,但是通过宏,您可以轻松地将其用于多条记录。
它的工作原理是这样的:merge/2 函数获取两条记录并将它们与空记录一起转换为列表以供参考(记录类型是在编译时定义的,并且必须是。这是“非动态”部分)。然后通过通用函数 merge/4 运行,该函数与列表一起使用,如果定义了元素,则从 A 获取元素,如果定义了则从 B 获取元素,或者最后从 Default(始终定义)获取元素。
这是代码(请原谅 StackOverflow 糟糕的 Erlang 语法突出显示):
%%%----------------------------------------------------------------------------
%%% @spec merge(RecordA, RecordB) -> #my_record{}
%%% RecordA = #my_record{}
%%% RecordB = #my_record{}
%%%
%%% @doc Merges two #my_record{} instances. The first takes precedence.
%%% @end
%%%----------------------------------------------------------------------------
merge(RecordA, RecordB) when is_record(RecordA, my_record),
is_record(RecordB, my_record) ->
list_to_tuple(
lists:append([my_record],
merge(tl(tuple_to_list(RecordA)),
tl(tuple_to_list(RecordB)),
tl(tuple_to_list(#my_record{})),
[]))).
%%%----------------------------------------------------------------------------
%%% @spec merge(A, B, Default, []) -> [term()]
%%% A = [term()]
%%% B = [term()]
%%% Default = [term()]
%%%
%%% @doc Merges the lists `A' and `B' into to a new list taking
%%% default values from `Default'.
%%%
%%% Each element of `A' and `B' are compared against the elements in
%%% `Default'. If they match the default, the default is used. If one
%%% of them differs from the other and the default value, that element is
%%% chosen. If both differs, the element from `A' is chosen.
%%% @end
%%%----------------------------------------------------------------------------
merge([D|ATail], [D|BTail], [D|DTail], To) ->
merge(ATail, BTail, DTail, [D|To]); % If default, take from D
merge([D|ATail], [B|BTail], [D|DTail], To) ->
merge(ATail, BTail, DTail, [B|To]); % If only A default, take from B
merge([A|ATail], [_|BTail], [_|DTail], To) ->
merge(ATail, BTail, DTail, [A|To]); % Otherwise take from A
merge([], [], [], To) ->
lists:reverse(To).
随意以任何你想要的方式使用它。