3-基本運算符
============
通過前幾章的學習,我們知道Elixir提供了 ```+,-,*,/``` 4個算術運算符,外加整數除法函數```div/2```和
取余函數```rem/2```。
Elixir還提供了```++```和```--```運算符來操作列表:
```elixir
iex> [1,2,3] ++ [4,5,6]
[1,2,3,4,5,6]
iex> [1,2,3] -- [2]
[1,3]
```
使用```<>```進行字符串拼接:
```elixir
iex> "foo" <> "bar"
"foobar"
```
Elixir還提供了三個布爾運算符:```or,and,not```。這三個運算符只接受布爾值作為 *第一個* 參數:
```elixir
iex> true and true
true
iex> false or is_atom(:example)
true
```
如果提供了非布爾值作為第一個參數,會報異常:
```elixir
iex> 1 and true
** (ArgumentError) argument error
```
運算符```or```和```and```可短路,即它們僅在第一個參數無法決定整體結果的情況下才執行第二個參數:
```elixir
iex> false and error("This error will never be raised")
false
iex> true or error("This error will never be raised")
true
```
>如果你是Erlang程序員,Elixir中的```and```和```or```其實就是```andalso```和```orelse```運算符。
除了這幾個布爾運算符,Elixir還提供```||```,```&&```和```!```運算符。它們可以接受任意類型的參數值。
在使用這些運算符時,除了 false 和 nil 的值都被視作 true:
```elixir
# 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還提供了 ```==,!=,===,!==,<=,>=,<,>``` 這些比較運算符:
```elixir
iex> 1 == 1
true
iex> 1 != 2
true
iex> 1 < 2
true
```
其中```==```和```===```的不同之處是后者在判斷數字時更嚴格:
```elixir
iex> 1 == 1.0
true
iex> 1 === 1.0
false
```
在Elixir中,可以判斷不同類型數據的大小:
```elixir
iex> 1 < :atom
true
```
這很實用。排序算法不必擔心如何處理不同類型的數據。總體上,不同類型的排序順序是:
```
number < atom < reference < functions < port < pid < tuple < maps < list < bitstring
```
不用強記,只要知道有這么回事兒就可以。