下面是记录类型
中的对象requirements = [] :: [term()],
我们提取如下的Requirements对象
Requirements = Records#record.requirements
我需要独立于any.latlong_radius元组的纬度,经度和纬度。我们如何提取出来?
"requirements": {
"supply_type": {
"$tuple": [1, {
"$tuple": ["mobile_app", "nil", "nil"]
}]
},
"has_app_name": true,
"any": {
"latlong_radius": {
"$tuple": [33.042334, -96.734884, 16093.4]
}
},
},
答案 0 :(得分:1)
-module(my).
-compile(export_all).
-record(requirements, {supply_type,
has_app_name,
any} ).
get_requirements() ->
#requirements{
supply_type = #{"$tuple" => [1, 2, 3]},
has_app_name = true,
any = #{"latlong_radius" =>
#{"$tuple" => [33.042334, -96.734884, 16093.4]}
}
}.
go() ->
Requirements = get_requirements(),
io:format("requirements: ~p~n", [Requirements]),
Any = Requirements#requirements.any,
#{"latlong_radius" :=
#{"$tuple" := [Lat, Lon, Rad]}
} = Any,
io:format("Lat: ~w, Lon: ~w, Rad: ~w~n", [Lat, Lon, Rad]).
在外壳中:
51> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
52> my:go().
requirements: {requirements,#{"$tuple" => [1,2,3]},
true,
#{"latlong_radius" =>
#{"$tuple" =>
[33.042334,-96.734884,16093.4]}}}
Lat: 33.042334, Lon: -96.734884, Rad: 16093.4
ok
另一方面,如果您的数据结构一直向下映射(这使您发布的有关记录和列表规范的所有内容都不相关):
-module(my).
-compile(export_all).
get_requirements() ->
#{"requirements" =>
#{
"supply_type" => #{"$tuple" => [1, 2, 3]},
"has_app_name" => true,
"any" => #{"latlong_radius" =>
#{"$tuple" => [33.042334, -96.734884, 16093.4]}
}
}
}.
go() ->
Requirements = get_requirements(),
io:format("requirements: ~p~n", [Requirements]),
#{"requirements" :=
#{
"any" :=
#{
"latlong_radius" :=
#{
"$tuple" := [Lat, Lon, Rad]
}
}
}
} = Requirements,
io:format("Lat: ~w, Lon: ~w, Rad: ~w~n", [Lat, Lon, Rad]).
在外壳中:
70> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
71> my:go().
requirements: #{"requirements" =>
#{"any" =>
#{"latlong_radius" =>
#{"$tuple" => [33.042334,-96.734884,16093.4]}},
"has_app_name" => true,
"supply_type" => #{"$tuple" => [1,2,3]}}}
Lat: 33.042334, Lon: -96.734884, Rad: 16093.4
ok
但是,在深层嵌套的地图中尝试正确设置模式匹配语法时,容易出错,因此我将改用maps:get/2
:
-module(my).
-compile(export_all).
get_requirements() ->
#{"requirements" =>
#{
"supply_type" => #{"$tuple" => [1, 2, 3]},
"has_app_name" => true,
"any" => #{"latlong_radius" =>
#{"$tuple" => [33.042334, -96.734884, 16093.4]}
}
}
}.
go() ->
Map = get_requirements(),
io:format("Map: ~p~n", [Map]),
Requirements = maps:get("requirements", Map),
Any = maps:get("any", Requirements),
LLR = maps:get("latlong_radius", Any),
#{"$tuple" := [Lat, Long, Radius]} = LLR,
io:format("Lat: ~w, Lon: ~w, Rad: ~w~n", [Lat, Long, Radius]).
简单得多。
答案 1 :(得分:0)
只需为变量分配双引号''
,如下所示:
Latlong_radius = Any#any.latlong_radius
Res = Latlong_radius#latlong_radius.'$tuple'