您的位置:首页 > 其它

Erlang 程序设计 学习笔记(三) 记录和映射组

2016-02-26 15:24 288 查看

Erlang 程序设计 学习笔记(三) 记录和映射组

记录

记录其实就是元组的另一种形式。通过使用记录,可以给元组里的各个元素关联一个名称。

何时使用记录

当你可以用一些预先确定且数量固定的原子来表示数据时;

当记录里的元素数量和元素名称不会随时间而改变时;

当存储空间是个问题时,典型的案例是你有一大堆元组,并且每个元组都有相同的结构。

records.erl

-module(records).
-record(book,{author , bookname  , chapters = 0}).


ErlangShell中的操作

2> 读取记录.
* 1: illegal character
2> rr("records.erl").
[book]
3>
3> 创建记录.
* 2: illegal character
3>
3> Shuihu = #book{author = "shinaian", bookname = "shuihuzhuan" }.
#book{author = "shinaian",bookname = "shuihuzhuan",
chapters = 0}
4> 更新记录.
* 1: illegal character
5> Shuihu2 = Shuihu#book{chapters = 36}.
#book{author = "shinaian",bookname = "shuihuzhuan",
chapters = 36}
6> 提取记录.
* 1: illegal character
7> #book{author = Author1 , bookname = BookName1 , chapters = N} = Shuihu.
#book{author = "shinaian",bookname = "shuihuzhuan",
chapters = 0}
8> Author1.
"shinaian"
9> BookName1.
"shuihuzhuan"
10> N.
0
11>


映射组

映射组是键--值对的关联性集合。键可以是任意的Erlang数据类型。

何时使用映射组

当键不能预先知道时用来表示键值数据结构;

 当存在大量不同的键时用来表示数据;

 当方便使用很重要而效率无关紧要时作为万能的数据结构使用;

 用作“自解释型”的数据结构,也就是说,用户容易从键名猜出值的含义;

 用来表示键值解析树,例如XML或配置文件;

 用JSON来和其他编程语言通信。

映射组的语法
#{Key1=> Value1 , Key2 => Value2 ,  ...    KeyN => ValueN}.   或者
#{Key1:= Value1 , Key2 := Value2 ,  ...    KeyN := ValueN}.
键和值可以是任何有效的Erlang数据类型

创建映射组
KVName = #{Key1 => value1,Key2 => value2 , Key3 => value3}.
更新映射组
NewKVName = KVName#{Key3 = newValue3}.
如果更新时候填错了Key值 会生成一个新的映射组
NewKVName2 = KVName#{Kye3 = newValue3}.
所以使用映射组的最佳方式是在首次定义某个键时总是使用Key => Value,而在修改具体某个键的值时都使用Key := Value
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: