elixir - 7 . keyword list, map
访问量: 1443
参考:https://elixir-lang.org/getting-started/keywords-and-maps.html
key word list:
1. 是个list
2. 元素是 :atom, xx 这样的形式。
list = [{:one, 1}, {:two, 2}]
[one: 1, two: 2]
list[:one] #=> 1
list[:two] #=> 2
还可以这样写: (跟ruby 的symbol.. hash非常像)
iex(18)> a = [five: 5]
[five: 5]
iex(19)> b = [{:five, 5}]
[five: 5]
iex(20)> a == b
true
一种缩写方式: (从上到下是等价的)
iex(21)> if(false, [{:do, :this}, {:else, :that}])
:that
iex(22)> if(false, [do: :this, else: :that])
:that
iex(23)> if false, [do: :this, else: :that]
:that
iex(24)> if false, do: :this, else: :that
:that
Map: 使用 %{}
map = %{:a => 1, 2 => :b} (可以看出, 常量也可以做key)
%{2 => :b, :a => 1}
iex(26)> map[:a]
1
iex(27)> map[2]
:b
iex(28)> map[:c]
nil
合并操作:
iex(30)> map
%{2 => :b, :a => 1}
iex(31)> %{map | :a => 4}
%{2 => :b, :a => 4}
Map 有一种非常方便的访问形式:
iex(32)> map
%{2 => :b, :a => 1}
iex(33)> map.2
** (SyntaxError) iex:33: syntax error before: "2"
iex(33)> map.a
1