一层一层取数据:完整示例与补充知识
这里保留原课的完整资料,供你按需查阅;主看板只讲本课的核心问题。
从 map 里的 list 读取值,再产生更新后的嵌套结构。
从书院记录读出第一门课,并把积分从 8 改为 9。
读取并更新课程积分
最后同时查看课程名与新积分。
原课完整示例(按说明选择运行环境)
Student = #{
name => <<"A-Qing">>,
courses => [#{title => <<"Erlang">>, points => 8}]
},
%% 先取课程 list,再匹配第一项
[Course | _] = maps:get(courses, Student),
Title = maps:get(title, Course),
%% 更新内层后,再放回外层 map
UpdatedCourse = Course#{points := 9},
Updated = Student#{courses := [UpdatedCourse]},
{Title, maps:get(points, hd(maps:get(courses, Updated)))}.得到 {<<"Erlang">>,9};Student 中的原积分仍为 8。
完整示例的执行步骤
- 先把嵌套读取拆成多个有名字的步骤。
- 内层课程 map 更新后,外层也要放入新课程 list。
- 所有更新都生成新 term。
原课补充说明
真实数据常由 map、list 和 tuple 叠在一起。先匹配外层,再处理内层,别一眼吞下整棵树。
maps:get/2 读取键。更新 map 使用 #{key := value},它返回新 map。
list 的头尾模式能取第一项。若 list 可能为空,应写出空 list 分支。
符号与术语对照
maps:get(Key, Map)- 读取 map 中指定键的值。
Map#{key := value}- 更新已经存在的键。
[Head | Tail]- 匹配非空 list 的第一项与剩余部分。
- 嵌套 term
- 一个集合中继续放其他集合,如 map 里放课程 list。
- map 更新
- 从旧 map 产生带新值的新 map;原值不改变。
原课完整练习
把 #{profile => #{city => <<"Xi'an">>}} 的城市改为 <<"Chengdu">>。
练习起点
Person = #{profile => #{city => <<"Xi'an">>}},
Profile = maps:get(____, Person),
Person#{profile := Profile#{city := ____}}.新 map 的城市是 <<"Chengdu">>。
查看提示
外层键是 profile,新值是一个 binary。
查看原课答案
答案参考
Person = #{profile => #{city => <<"Xi'an">>}},
Profile = maps:get(profile, Person),
%% 先更新内层,再放回外层
Person#{profile := Profile#{city := <<"Chengdu">>}}.Map#{key := value} 会直接改掉 Map 吗?
不会。它返回新 map;旧变量仍指向旧值。
原课要点
- 嵌套数据要分层读取。
:=更新已存在的 map 键。- 旧 term 不会被原地修改。