0%

erlang 17+ map,record互转

在OTP17+版本,增加了maps数据结构,maps相对record有很多优良特性
但是,很多模块(ets,mnesia)还是以record为基础
maps,record互转很有必要

直接贴代码:

m2r.erlview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
%% ===========================================================================
%% @doc

%% @end
%% ===========================================================================
-module(m2r).
-author(zhaoming).
-version(1.0).
-date('2016-06-08').

-export([
test/0
]).

-record(mapRecord, {
a = 1
,b = 3
,c = 2
,d = 4
}).

-define(map_to_record(Map, RecordName),
%% list_to_tuple(
%% lists:map(
%% fun({__K__, __V__}) -> maps:get(__K__, Map, __V__) end,
%% lists:zip([RecordName|record_info(fields, RecordName)], tuple_to_list(#RecordName{}))
%% )
%% )
list_to_tuple( [maps:get(__K__, Map, __V__) || {__K__, __V__} <- lists:zip([RecordName|record_info(fields, RecordName)], tuple_to_list(#RecordName{})) ] )
).

-define(record_to_map(RecordName, Record),
%% lists:foldl(
%% fun({__K__, __V__}, __Map__) -> maps:put(__K__, __V__, __Map__) end,
%% #{},
%% lists:zip(['__name__'|record_info(fields, RecordName)], tuple_to_list(Record))
%% )
maps:from_list(lists:zip(['__name__'|record_info(fields, RecordName)], tuple_to_list(Record)))
).

test() ->
Map = #{'__name__' => mapRecord, "a" => 1, b => 2},
io:format("~p~n", [Map]),
K = 1,
R = ?map_to_record(Map, mapRecord),
io:format("~p~n", [R]),
?record_to_map(mapRecord, #mapRecord{}).