URL
試した環境
- Ubuntu Server 14.04 LTS
- Erlang/OTP 18
- Elixir 1.0.4
Basic operators
文字列の連結:<>
iex> "foo" <> "bar"
"foobar"
短絡ブール演算子: and
, or
, not
引数がtrueやfalseでないと失敗する
iex(2)> true and true
true
iex(3)> false or true
true
iex> not true
false
iex> false or is_atom(:example)
true
iex> 1 and true
** (ArgumentError) argument error: 1
短絡演算子なので、演算子の第一引数を評価した段階で式全体の値が定まらない場合のみ第二引数を評価する。
unknown_function()は、定義していないが、下記の初めの2つの例では、評価されないので失敗しない。
iex> false and unknown_function()
false
iex> true or unknown_function()
true
iex> true and unknown_function()
** (RuntimeError) undefined function: unknown_function/0
ちなみにandとorは、Erlangのandalsoとorelse演算子と同じ。
論理演算子: ||
, &&
, !
どんな型でも引数として受け入れる。falseとnil以外はtrueとして評価される。
iex> 1 || true
1
iex> false || 11
11
iex> nil && 13
nil
iex> true && 17
17
iex> !true
false
iex> !1
false
iex> !nil
true
iex> !11
false
使い分けの目安としては、引数がbooleanの場合は、and, or, notを使い、引数のどれかがnon-booleanの場合は、&&, ||, !を使う。
比較演算子:==
, !=
, ===
, !==
, <=
, >=
, <
, >
iex> 1 == 1
true
iex> 1 != 2
true
iex> 1 < 2
true
比較するものがfloatの場合は、==
と===
の違いに気をつける必要がある。===
の方がより厳密に比較する。floatを扱っている場合は、注意が必要。
iex> 1 == 1.0
true
iex> 1 === 1.0
false
iex> 1 != 1.0
false
iex> 1 !== 1.0
true
ちなみにErlangだと===
は=:=
(同一である), !=
は/=
(等価ではない), !==
は=/=
(同一ではない)と対応する。
==
と===
の使い方としては、飛行機本に従うなら大抵の場合は、===
を使った方が良い。
実用主義的な理由で異なる型の比較もできる。
iex> 1 < :atom
true
比較の順番は次のように定義されている。
ソートするために、異なるデータ型を心配する必要はない。
number < atom < reference < functions < port < pid < tuple < maps < list < bitstring
上記の定義は、例えば、どんな大きさの数でもどんなatomよりは小さいということを意味している。
iex> 312312335345 < :a
true
iex> :a < is_atom(:a)
true
iex> :a > is_atom(:a)
false
iex(47)> :abc < {:a,:b}
true