官术网_书友最值得收藏!

Booleans

Elixir has three values related to Boolean operations: true, false, and nil (where nil represents the absence of value—similar to null in most other languages). However, those are just some syntatic sugar, as internally they are represented as atoms of the same name, as you can see in the following example:

iex> true == :true
true
iex> false == :false
true
iex> nil == :nil
true

You have the common Boolean operators, orand, and not:

iex> true or false
true
iex> true and false
false
iex> not false
true

However, these operators are type-strict in their first argument: they only accept true or false. If you pass anything else as an argument, you'll get BadBooleanError.

This is where the concept of truthiness and falseness enters. Similar to what happens in Ruby or C, false and nil are treated as falsey values, and everything else is considered to be truthy. The operators that work with falsey and truthy values are && (and), || (or), and ! (not):

iex> "a value" || false
"a value"
iex> "a value" && false
false
iex> nil && "a value"
nil
iex> !"a value"
false

Notice how these operators short circuit depending on the arguments. With ||, it returns the first value that's truthy, whereas with &&, it returns the first falsey value (in both cases, in the event those conditions never happen, they return the last value).

You also have the other normal comparison operators, such as greater than (>) and inequality (!=)—you can find the full list at https://hexdocs.pm/elixir/operators.html. The one that's worth pointing out is the strict equality operator, which, besides comparing values, compares types:

iex> 3 == 3.0
true
iex> 3 === 3.0
false
主站蜘蛛池模板: 宝丰县| 田林县| 新蔡县| 定陶县| 西昌市| 巴彦县| 平乐县| 聂拉木县| 南江县| 嘉峪关市| 闵行区| 泸州市| 汉阴县| 林甸县| 曲阜市| 新丰县| 得荣县| 衡阳县| 金川县| 江津市| 柳州市| 永福县| 曲阜市| 安塞县| 定安县| 鄱阳县| 金乡县| 奉化市| 新竹县| 宜都市| 即墨市| 伊金霍洛旗| 沧州市| 新余市| 孟村| 商河县| 离岛区| 上高县| 临朐县| 得荣县| 青冈县|