字典:散列表、散列字典、关键字列表、集合与结构体

字典

  散列表和散列字典都实现了Dict的行为。Keyword模块也基本实现了,不同之处在于它支持重复键。

  Eunm.into可以将一种类型的收集映射转化成另一种。

defmodule Sum dodef values(dict) dodict |> Dict.values |> Enum.sumend
endhd = [ one: 1, two: 2, three: 3 ] |> Enum.into HashDict.new
IO.puts Sum.values(hd)      #=>6

  Dict相关API

kw_list = [name: "Dave", likes: "Programming", where: "Dallas"]
hashdict = Enum.into kw_list, HashDixt.new
map = Enum.into kw_list, Map.newkw_list[:name]        #=>"Dave"
hashdict[:likes]        #=>"Programming"
map[:where]        #=>"Dallas"hashdict = Dict.drop(hashdict, [:where, :likes])        #=>HashDict<[name: "Dave"]>
hashdict = Dict.put(hashdict, :also_likes, "Ruby)        #=>HashDict<[name: "Dave", also_likes: "Ruby"]>
combo = Dict.merge(map, hashdict)        #合并=>%{also_likes: "Ruby", likes: "Programming", name: "Dave", where: "Dallas"}

  例子:

people = [%{ name: "Grumpy, height: 1.24 },%{ name: "Dave", height: 1.88 },%{ name: "Dopey", height: 1.32 },%{ name: "Shaquille", height: 2.16 },%{ name: "Sneezy", height: 1.28 }]
for person = %{ height: height } <- people,     #将列表中的散列表绑定到person ,并将高度值绑定到heightheight > 1.5,            #筛选出高度高于1.5的do: IO.inspect person    

  例子2:

def book(%{name: name, height: height})
when height > 1.9 do...
enddef book(%{name: name, height: height})
when height < 1.3 do...
enddef book(person) do...
endpeople |> Enum.each(&HotelRoom.book/1)

 

更新散列表

  new_map = %{ old_map | key => value, ...},会创建一个新的散列表,它是旧散列表的拷贝,但是管道运算符右边与键所对应的值会被更新。

m = %{ a: 1, b: 2, c: 3 }
m1 = %{ m | b: "two", c: "three" }        #%{ a: 1, b: "two, c: "three" }#要增加新的键值需要使用Dict.put_new/3函数

 

结构体

  结构体就是模块,它封装了一个有限形式的散列表。有限是因为键必须为原子,并且这些散列表不具备Dict和Access特性。使用defstruct来定义散列表的性质。

  结构体的使用就相当于是散列表一样,只不过结构体有默认参数。

defmodule Subscriber dodefstruct name: "", paid: false, over_18: true
ends1 = %Subscriber{}        #=>%Subscriber{name: "", over_18: true, paid: false }
s2 = %Subscriber{name: "Mary", paid: true}        #=>%Subscriber{name: "Mary", over_18: true, paid: true }匹配
s2.name            #通过点标记访问,键必须为原子,符合结构体的特性
%Subscriber{name: a_name} = s3
a_name            #=>"Mary"

更新
s3 = %Subscriber{ s2 | name: "Marie" }

  例子:

defmodule Attendee dodefstruct name: "", paid: false, over_18: truedef may_attend_after_party(attendee = %Attendee{}) do    #函数参数使用 %Attendee{} 接受结构体attendee.paid && attendee.over_18enddef print_vip_badge(%Attendee{name: name}) when name != "" doIO.puts "Very cheap badge for #{name}"enddef print_vip_bage(%Attendee{}) foraise "missing name for badge"end
end

  

  散列表实现了Access协议,所以可以使用 [] 访问。我们可以给结构体添加这个功能。

defmodule Attendee do@derive Accessdefstruct name: "", over_18: false
enda = %Attendee{name: "Sally", over_18: true}
a[:name]          #=> "Sally

 

嵌套字典结构

  字典类型可以让键和值相关联,这些值本身也可以是字典类型。

defmodule Customer dodefstruct name: "", company: ""
enddefmodule BugReport dodefstruct owner: %{}, details: "", serverity: 1
endreport = %BugReport{owner: %Customer{name: "Dave", company: "Pragmatic"}, detail: "broken"}#访问
report.owner.company#更新/修改
report = %BugReport{ report | owner: %Customer{ report.owner | company: "PragProg" }}#put_in可以设置嵌套结构里面的值
put_in(report.owner.company, "PargProg")#update_in可以让我们在结构体上的某一个值上执行一个函数
update_in(report.owner.name, &("Mr. " <> &1))    #连接 "Mr. "和name

 

转载于:https://www.cnblogs.com/lr1402585172/p/11498408.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/384207.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++11 学习笔记 lambda表达式

http://blog.csdn.net/fjzpdkf/article/details/50249287 lambda表达式是C11最重要也最常用的一个特性之一。lambda来源于函数式编程的概念&#xff0c;也是现代编程语言的一个特点。 一.函数式编程简介 定义&#xff1a;简单说&#xff0c;“函数式编程”是一种“编程范式”。…

Cutting Codeforces Round #493 (Div. 2)

Cutting There are a lot of things which could be cut — trees, paper, “the rope”. In this problem you are going to cut a sequence of integers. There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited bud…

Enum、Stream

Enum 其常见用法见&#xff1a;https://cloud.tencent.com/developer/section/1116852 在sort时&#xff0c;如果要获得稳定的排序结果&#xff0c;要使用< 而不是 <。 Stream Stream是延迟处理的&#xff0c;而Enum是贪婪的&#xff0c;则意味着传给它一个收集&#xff…

linux网络编程之posix 线程(三):posix 匿名信号量与互斥锁 示例生产者--消费者问题

http://blog.csdn.net/jnu_simba/article/details/9123603 一、posix 信号量 信号量的概念参见这里。前面也讲过system v 信号量&#xff0c;现在来说说posix 信号量。 system v 信号量只能用于进程间同步&#xff0c;而posix 信号量除了可以进程间同步&#xff0c;还可以线程间…

洛谷P1080-国王游戏-贪心+高精度

P1080-国王游戏 啊啊啊&#xff0c;刚才已经写了一次了&#xff0c;但是Edge浏览器不知道为什么卡住了&#xff0c;难受。 好吧&#xff0c;其实是一道可做题&#xff0c;分析得到的贪心策略就是就是将a * b小的放在前面&#xff08;其他的懒得说了&#xff09;&#xff0c;主要…

字符串与二进制

单引号字符串会被表示成整数值列表。 &#xff1f;c返回字符 c 的整数编码。下面这个例子用于解析字符列表表示法&#xff0c;该表示法用于表示一个任意的有符号的十进制数据。 defmodule Parse dodef number([ ?- | tail ]) do_number_digits(tail, 0) * -1enddef number([ ?…

P1092虫食算-深度优先搜索+玄学剪枝

P1092虫食算 这道题的思想并不复杂&#xff0c;可是难点在于各种玄学剪枝。在仔细研究了题解大佬的剪枝原理后终于氵了过去。 先上代码&#xff1a; #include<cstdio> #include<cstring> #include<algorithm> using namespace std;const int MAXN100; int n…

多进程

使用spawn创建一个新进程&#xff0c;其第一个参数是模块名、第二个参数是函数名、第三个参数是参数列表。spawn会返回一个进程标识符&#xff0c;通常叫做PID。 defmodule Spawn1 dodef greet doreceive do{sender, msg} ->send sender, { :ok, "Hello #{msg}" }…

Linux socket编程(二) 服务器与客户端的通信

http://www.cnblogs.com/-Lei/archive/2012/09/04/2670964.html上一篇写了对套接字操作的封装&#xff0c;这一节使用已封装好的Socket类实现服务器与客户端的通信&#xff08;Socket的定义见上篇Socket.h) 服务器端&#xff1a; ServerSocket.h #ifndef SERVERSOCKET_H #defin…

OTP服务器

defmodule Sequence.Server douse GenServerdef handle_call( :next_number, _from, current_number) do{ :reply, current_number, current_number 1}  #reply告诉OTP将第二个元素返回给客户端end end use的效果将OTP GenServer的行为添加到当前模块。这样它就可以处理所有…

洛谷P1040-加分二叉树-dp+二叉树

P1040-加分二叉树 这道题放在深度优先搜索的训练题中&#xff0c;可是我实在没有看出来应该怎么搜索。看了题解以后才看出来是一个很简单的dp(我果然还是太菜了) 看出dp并且算出来最大的分数不是很复杂&#xff0c;关键是输出给定中序遍历序列的二叉树的先序遍历&#xff0c;要…

UNIX网络编程:I/O复用技术(select、poll、epoll)

http://blog.csdn.net/dandelion_gong/article/details/51673085 Unix下可用的I/O模型一共有五种&#xff1a;阻塞I/O 、非阻塞I/O 、I/O复用 、信号驱动I/O 、异步I/O。此处我们主要介绍第三种I/O符复用。 I/O复用的功能&#xff1a;如果一个或多个I/O条件满足&#xff08;输…

解决iex -S mix报错

执行iex -S mix命令的时候会遇到如下错误&#xff1a; 执行 mix deps.get 然后就可以运行 iex -S mix了 其中&#xff0c;有可能会出现 按照其网站下载相应文件&#xff0c;复制到项目根目录下&#xff0c;然后执行命令&#xff08;mix local.rebar rebar ./rebar&#xff09;即…

贪心算法——选择不相交区间问题

题目描述&#xff1a;设有n个活动的集合&#xff0c;其中每个活动都要求使用同一个资源&#xff0c;而在同一时间内只有一个活动能够使用这一资源&#xff0c;每个活动i都有一个要求使用该资源的起始时间si和一个结束时间fi(si<fi)&#xff0c;如果选择了活动i&#xff0c;则…

Anker—工作学习笔记

http://www.cnblogs.com/Anker/archive/2013/08/17/3263780.html 1、基本知识 epoll是在2.6内核中提出的&#xff0c;是之前的select和poll的增强版本。相对于select和poll来说&#xff0c;epoll更加灵活&#xff0c;没有描述符限制。epoll使用一个文件描述符管理多个描述符&am…

Supervisor监控

可参考&#xff1a;https://www.cnblogs.com/wang_yb/archive/2016/06/08/5564459.html &#xff1a;https://segmentfault.com/a/1190000007379204 转载于:https://www.cnblogs.com/lr1402585172/p/11551488.html

深度搜索剪枝——数的划分

【题目描述】将整数n分成k份&#xff0c;且每份不能为空&#xff0c;问有多少种分法&#xff1f; 【输入格式】两个整数n,m(6<n<200,2<m<6) 【输出格式】输出不同的分法数 【样例输入】7 3 【样例输出】4 对于这种搜索题&#xff0c;关键就在于剪枝&#xff1a;确定…

Linux网络编程——tcp并发服务器(I/O复用之select

http://blog.csdn.net/lianghe_work/article/details/46519633 与多线程、多进程相比&#xff0c;I/O复用最大的优势是系统开销小&#xff0c;系统不需要建立新的进程或者线程&#xff0c;也不必维护这些线程和进程。 代码示例&#xff1a; [csharp] view plaincopy #include &…

ets

:ets.new(table_name, pattern) 第一个参数是表名&#xff0c;第二个参数是表的设置选项。 :set  一个key&#xff0c;一个数据&#xff0c;无序 :ordered_set  一个key&#xff0c;一个数据&#xff0c;有序&#xff1b; 1 1.0 :bag  一个key&#xff0c;多个数据&…

贪心算法-区间选点问题-种树

【题目描述】一条街道的一边有几座房子。因为环保原因居民想要在路边种些树&#xff0c;路边的地区被分割成n块&#xff0c;并被编号为1~n。每块大小为一个单位尺寸且最多可总一棵树。每个居民想在门前种些树并制定了三个数b,e,t&#xff0c;这三个数代表居民想在b和e之间最少种…