Elixir-example-logical
提供:Dev Guides
Elixir-論理演算子
Elixirは6つの論理演算子を提供します:and、or、not、&&、||および! 最初の3つの andまたはnot は厳密なブール演算子です。つまり、最初の引数がブールであることを期待しています。 非ブール引数はエラーを発生させます。 次の3つ、* &&、||および!は厳密ではないため、最初の値を厳密にブール値にする必要はありません。 それらは、厳密な対応物と同じように機能します。 変数 *A が真を保持し、変数 B が20を保持すると仮定します-
Operator | Description | Example |
---|---|---|
and | Checks if both values provided are truthy, if yes then returns the value of second variable. (Logical and). | A and B will give 20 |
or | Checks if either value provided is truthy. Returns whichever value is truthy. Else returns false. (Logical or). | A or B will give true |
not | Unary operator which inverts the value of given input. | not A will give false |
&& | Non-strict and. Works same as *and *but does not expect first argument to be a Boolean. | B && A will give 20 |
Non-strict* or*. Works same as *or *but does not expect first argument to be a Boolean. | B | |
A will give true | ! | Non-strict* not*. Works same as not but does not expect the argument to be a Boolean. |
注- and _、 or 、 && 、および || _は短絡演算子です。 これは、 and の最初の引数がfalseの場合、2番目の引数をさらにチェックしないことを意味します。 or の最初の引数がtrueの場合、2番目の引数はチェックされません。 例えば、
false and raise("An error")
#This won't raise an error as raise function wont get executed because of short
#circuiting nature of and operator.
例
次のコードを試して、Elixirのすべての算術演算子を理解してください。
a = true
b = 20
IO.puts("a and b " <> to_string(a and b))
IO.puts("a or b " <> to_string(a or b))
IO.puts("not a " <> to_string(not a))
IO.puts("b && a" <> to_string(b && a))
IO.puts("b || a " <> to_string(b || a))
IO.puts("!a " <> to_string(!a))
上記のプログラムは、次の結果を生成します-
a and b 20
a or b true
not a false
b && a true
b || a 20
!a false