Elixir Introduction 2

不可变性

Elixir中,所有的值都是不可变的。

基础

原子

院子是常量,用于表示某些东西的名字,以冒号(:)开头

元组

元组被创建就无法修改,如:{1, 2}
用于模式匹配

1
2
3
4
5
6
7
8
9
iex(4)> {status, count, action} = {:ok, 42, "next"}
{:ok, 42, "next"}
iex(5)> status
:ok
iex(6)> count
42
iex(7)> action
"next"
iex(8)>

散列表

1
2
3
4
5
6
7
8
iex(9)> states = %{"AL" => "Alabama", "WI" => "Wisconsin"}
%{"AL" => "Alabama", "WI" => "Wisconsin"}
iex(10)> states["AL"]
"Alabama"
iex(11)> colors = %{ red: 0xff0000 }
%{red: 16711680}
iex(12)> colors.red
16711680

匿名函数

函数定义

  1. 匿名函数用fn关键字创建;
  2. 函数定义中可以省略圆括号;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
iex(1)> sum = fn (a, b) -> a + b end
#Function<12.52032458/2 in :erl_eval.expr/5>
iex(2)> sum.(1, 2)
3
iex(3)> greet = fn -> IO.puts "Hello" end
#Function<20.52032458/0 in :erl_eval.expr/5>
iex(4)> greet.()
Hello
:ok
iex(5)> f1 = fn a, b -> a * b end
#Function<12.52032458/2 in :erl_eval.expr/5>
iex(6)> f1.(5, 6)
30
iex(7)> f2 = fn -> 99 end
#Function<20.52032458/0 in :erl_eval.expr/5>
iex(8)> f2.()
99
iex(9)> swap = fn {a, b} -> {b, a} end
#Function<6.52032458/1 in :erl_eval.expr/5>
iex(10)> swap.({6, 8})
{8, 6}
iex(11)> list_concat = fn l1, l2 -> l1 ++ l2 end
#Function<12.52032458/2 in :erl_eval.expr/5>
iex(12)> list_concat.([:a, :b], [:c, :d])
[:a, :b, :c, :d]
iex(13)> sum = fn a, b, c -> a + b + c end
#Function<18.52032458/3 in :erl_eval.expr/5>
iex(14)> sum.(1, 2, 3)
6
iex(15)> pair_tuple_to_list = fn {a, b} -> [a, b] end
#Function<6.52032458/1 in :erl_eval.expr/5>
iex(16)> pair_tuple_to_list.({1234, 5678})
[1234, 5678]

函数重载

函数重载取决于传入的参数类型和内容,通过模式匹配来选择要运行的子句

1
2
3
4
5
6
7
8
9
10
iex(1)> handle_open = fn
...(1)> {:ok, file} -> "Read data: #{IO.read(file, :line)}"
...(1)> {_, error} -> "Error: #{:file.format_error(error)}"
...(1)> end
#Function<6.52032458/1 in :erl_eval.expr/5>
iex(2)> handle_open.(File.open('donotexistfile'))
"Error: no such file or directory"
iex(3)> handle_open.(File.open('/tmp/test.py'))
"Read data: #!/usr/bin/env python\n"
iex(4)> handle_open.(File.open('/tmp/test.py'))
0%