基本操作
在前面的章节中,我们看到了 Elixir 提供+,-,*,/如算术运算符,再加上功能div/2和rem/2整数除法和余数。
Elixir 还提供++和--操纵列表:
iex> [1, 2, 3] ++ [4, 5, 6] [1, 2, 3, 4, 5, 6] iex> [1, 2, 3] -- [2] [1, 3]
字符串连接用<>完成:
iex> "foo" <> "bar" "foobar"
Elixir 还提供了三种布尔运算符:or,and和not。这些操作符是严格的,他们期望布尔(true或false)作为它们的第一个参数:
iex> true and true true iex> false or is_atom(:example) true
提供非布尔值将引发异常:
iex> 1 and true ** (BadBooleanError) expected a boolean on left-side of "and", got: 1
or和and是短路 short-circuit 运算符。如果左侧不足以确定结果,他们只执行右侧:
iex> false and raise("This error will never be raised")
false
iex> true or raise("This error will never be raised")
true注意:如果你是一个 Erlang 开发,
and和or在实际 Elixir 映射到andalso与orelse在 Erlang 中的运算符。
除了这些布尔运算符,Elixir 还提供||,&&以及!其接受任何类型的参数。对于这些运算符,除了false和nil将评估为 true 的所有值:
# or iex> 1 || true 1 iex> false || 11 11 # and iex> nil && 13 nil iex> true && 17 17 # ! iex> !true false iex> !1 false iex> !nil true
作为一个经验法则,使用and,or以及not当你期待布尔值时。如果任何参数为非布尔值,使用&&,||和!。
Elixir 也提供了==,!=,===,!==,<=,>=,<,和>作为比较操作符:
iex> 1 == 1 true iex> 1 != 2 true iex> 1 < 2 true
==和===之间的差是比较整数和浮当后者是更严格的:
iex> 1 == 1.0 true iex> 1 === 1.0 false
在 Elixir 中,我们可以比较两种不同的数据类型:
iex> 1 < :atom true
我们可以比较不同数据类型的原因是实用主义。排序算法不需要担心不同的数据类型以进行排序。总体排序顺序如下所示:
number < atom < reference < function < port < pid < tuple < map < list < bitstring
你并不需要记住这个顺序,只要知道这个顺序存在就足够了。
有关操作员(和订购)的参考信息,请查看运算符的参考页面。
在下一章中,我们将讨论一些基本功能,数据类型转换和一些控制流。
