安装
MAC 平台用 brew 安装
brew update
brew install elixir
如果没有 erlang 环境,上面的命令会自定安装 erlang 的环境。
基本数据类型
iex> 1 # integer
iex> 0x1F # integer
iex> 1.0 # float
iex> true # boolean
iex> :atom # atom / symbol
iex> "elixir" # string
iex> [1, 2, 3] # list
iex> {1, 2, 3} # tuple
数学运算
/ 总是返回浮点数,如果需要整数运算,使用 div 和 rem 函数
iex> div(1, 2)
div(1, 2)
0
iex> rem(1, 2)
rem(1, 2)
1
二进制,八进制,十六进制表示方式
iex> 0b10000
0b10000
16
iex> 0o20
0o20
16
iex> 0x10
0x10
16
原子
原子是一种常量,变量名就是它的值。有2种写法:
- :原子名
- :"原子名"
列表
列表中可以包含任意数据类型
iex> [1, 1.2, true, "hello"]
[1, 1.2, true, "hello"]
[1, 1.2, true, "hello"]
列表可以通过 ++/– 来拼接
iex> [1, 2, true] ++ [1, 3, false]
[1, 2, true] ++ [1, 3, false]
[1, 2, true, 1, 3, false]
iex> [1, 2, true, 2, false] -- [1, 3, false, 2]
[1, 2, true, 2, false] -- [1, 3, false, 2]
[true, 2]
可以通过 hd/1 tl/1 函数来获取头部和头部以外的部分
iex> hd([1, 2, true])
hd([1, 2, true])
1
iex> tl([1, 2, true])
tl([1, 2, true])
[2, true]
对一个空列表执行 hd/1 和 tl/1 会报错
iex> hd([])
hd([])
** (ArgumentError) argument error
:erlang.hd([])
iex> tl([])
tl([])
** (ArgumentError) argument error
:erlang.tl([])
列表和元组区别
- 列表是以链表形式在内存存储的,元组是在内存中连续存储的。
- 列表前置拼接操作很快,后置拼接操作慢
后置拼接时修改了原列表的最后一个元素,所以会重建整个列表
- 函数的返回值一般用元组来保存
字符串和字符列表
- 双引号包裹的是字符串: 字符串中存储的是 byte
- 单引号包裹的是字符列表: 字符列表中存储的是每个字符的 codepoint
基本运算符
- 算术运算 + - * / div/2 rem/2
- 列表拼接 ++ –
字符串拼接 <>
iex> "foo" <> "bar"
"foo" <> "bar"
"foobar"
- 布尔运算符
- 比较运算符
= !
=
!== <= >= < >
模式匹配
- elixir 中 = 是模式匹配运算符
可以给list 的 head 和 tail 赋值
iex> [h|t]=[1,2,3]
[1, 2, 3]
iex> h
1
iex> t
[2, 3]
控制语句
case
iex> case {1, 2, 3} do
...> {4, 5, 6} ->
...> "This clause won't match"
...> {1, x, 3} ->
...> "This clause will match and bind x to 2 in this clause"
...> _ ->
...> "This clause would match any value"
...> end
case的条件中可以加入判断的表达式,比如下面的 (when x > 0)
iex> case {1, 2, 3} do
...> {1, x, 3} when x > 0 ->
...> "Will match"
...> _ ->
...> "Won't match"
...> end
cond
iex> cond do
...> 2 + 2 == 5 ->
...> "This will not be true"
...> 2 * 2 == 3 ->
...> "Nor this"
...> 1 + 1 == 2 ->
...> "But this will"
...> 3 + 3 == 6 ->
...> "But this will too"
...> end
"But this will"
只会执行第一个匹配上的分支
if/unless
iex> if nil do
...> "This won't be seen"