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
相关文章推荐
- Unity NGUI之ScrollView扩展-1
- Web API 强势入门指南
- DataTable
- Gmail打不开登录不了邮箱最新解决方法!
- wireshark 二 报文解析
- iOS支付宝开发遇到的问题
- Linux 启动流程即init程序分析--2
- ZOJ-3778-Talented Chef【11th浙江省赛】【贪心】
- hdu 1540 线段树区间合并
- 安装php连接redis cluster扩展
- java 发送邮件(并添加附件)
- ExtJS4中initComponent和constructor的区别
- 探究问题:ssh+extjs 权限角色用户功能的实现
- uva208 -Firetruck (双向搜索进行剪枝)
- Android中日期时间格式转换
- make: ./libtool:command not found
- JS时间格式化
- activemq启动不起来,报错Address already in use: JVM_Bind
- angularJs 指令的用法
- Sublime3和Chrome配置自动刷新网页【实测可用】