DEV Community

gumi TECH for gumi TECH Blog

Posted on • Updated on

Elixir入門 03: 演算子の基本

本稿はElixir公式サイトの許諾を得て「Basic operators」の解説にもとづき、加筆補正を加えてElixirの基本的な演算子についてご説明します。

算術演算

四則演算はつぎのとおりです。演算子/による除算は結果が整数であっても、浮動小数点数に変わることにご注意ください。

iex> 4 + 2
6
iex> 4 - 2
2
iex> 4 * 2
8
iex> 4 / 2
2.0
iex> (1 + 2) / 3 + 4 * 5
21.0
Enter fullscreen mode Exit fullscreen mode

整数の割り算で、商の整数部を得るにはdiv/2関数を用います。また、整数の剰余を求めるのはrem/2関数です。

iex> div(10, 2)
5
iex> rem(10, 3)
1
Enter fullscreen mode Exit fullscreen mode

リストの加減算

リストに別のリストの要素を加えるときは演算子++/2、差し引くには--/2を用います。

iex> list ++ ["Cherry"]
[3.14, :pie, true, "Apple", "Cherry"]
iex> ["π"] ++ list
["π", 3.14, :pie, true, "Apple"]
iex> list -- [true, false]
[3.14, :pie, "Apple"]
Enter fullscreen mode Exit fullscreen mode

文字列の演算

文字列をつなぐ演算子は<>です。

iex> name = "alice"
iex> "hello " <> name
"hello alice"
Enter fullscreen mode Exit fullscreen mode

アトムは#{}でかこんで文字列補間することにより、文字列に含めることができます。

iex> "hello #{:world}"
"hello world"
Enter fullscreen mode Exit fullscreen mode

論理和と論理積および否定

論理和||と論理積&&の演算子は、左オペランド(被演算子)を論理値として評価します。Elixirではfalsenilを除く値はtrueと評価されます。それぞれの演算子が返す値はつぎのふたつの表001と002のとおりです。

表001■論理和||演算子

左オペランドの評価 返される値
true 左オペランドの値
false 右オペランドの値

表002■論理和&&演算子

左オペランドの評価 返される値
true 右オペランドの値
false 左オペランドの値
iex> -1 || true
-1
iex> false || 2
2
iex> nil && 3
nil
iex> true && 4
4
Enter fullscreen mode Exit fullscreen mode

否定の演算子!は、オペランドを論理値として評価したうえで、反転した論理値が返されます。

iex> !true
false
iex> !1
false
iex> !nil
true
Enter fullscreen mode Exit fullscreen mode

さらに、厳密な論理演算子orandおよびnotがあります。いずれも、はじめのオペランドは必ず論理値でなければなりません。

iex> is_atom(:example) and 1
1
iex> false or 1
1
iex> not is_number(false)
true
iex> 1 and true
** (BadBooleanError) expected a boolean on left-side of "and", got: 1
iex> not 1
** (ArgumentError) argument error
    :erlang.not(1)
Enter fullscreen mode Exit fullscreen mode

論理和および論理積演算子が左オペランドを返す場合、右オペランドは実行されません。たとえば、実行されれば引数をエラーとして出力するraise/1関数が右オペランドに置かれたつぎのコードはエラーになりません。

iex> false and raise("実行されればエラー")
false
iex> true || raise("実行されればエラー")
true
Enter fullscreen mode Exit fullscreen mode

比較

値の大小や等しいか等しくないかの比較をする演算子はつぎのとおりです。

  • ==: 等しい
  • !=: 等しくない
  • <=: 以下
  • >=: 以上
  • <: 小さい
  • >: 大きい
iex> 1 > 2
false
iex> 1 != 2
true
iex> 1 == 1
true
iex> 1 <= 2
true
Enter fullscreen mode Exit fullscreen mode

さらに、厳密な等価===と不等価!==の演算子があります。

iex> 1 == 1.0
true
iex> 1 === 1.0
false
Enter fullscreen mode Exit fullscreen mode

Elixirでは、異なった型のデータでも大小が比べられます。データのソートを考えたとき、型を心配しなくて済むためです。

iex> :hello > 999
true
iex> {:hello, :world} > [1, 2, 3]
false
Enter fullscreen mode Exit fullscreen mode

データ型による大きさの順序はつぎのとおりです(「Term ordering」参照)。

number < atom < reference < function < port < pid < tuple < map < list < bitstring
Enter fullscreen mode Exit fullscreen mode

Elixir入門もくじ

番外

Top comments (0)