3-基本运算符
使用<>
进行字符串拼接:
iex> "foo" <> "bar"
"foobar"
Elixir还提供了三个布尔运算符:or,and,not
。这三个运算符只接受布尔值作为 第一个 参数:
iex> true and true
true
iex> false or is_atom(:example)
true
如果提供了非布尔值作为第一个参数,会报异常:
iex> false and error("This error will never be raised")
false
iex> true or error("This error will never be raised")
true
除了这几个布尔运算符,Elixir还提供||
,&&
和!
运算符。它们可以接受任意类型的参数值。
在使用这些运算符时,除了 false 和 nil 的值都被视作 true:
iex> 1 || true
1
iex> false || 11
11
# and
iex> nil && 13
nil
iex> true && 17
17
false
iex> !1
false
iex> !nil
true
根据经验,当参数确定是布尔时,使用and
,or
和not
;
如果非布尔值(或不确定是不是),用&&
,||
和!
。
其中==
和===
的不同之处是后者在判断数字时更严格:
iex> 1 == 1.0
true
iex> 1 === 1.0
false
在Elixir中,可以判断不同类型数据的大小:
iex> 1 < :atom
这很实用。排序算法不必担心如何处理不同类型的数据。总体上,不同类型的排序顺序是: