- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 293字
- 2021-08-05 10:42:45
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, or, and, 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
- UML和模式應用(原書第3版)
- Pandas Cookbook
- C語言程序設計基礎與實驗指導
- C#程序設計(慕課版)
- Network Automation Cookbook
- PHP+MySQL網站開發技術項目式教程(第2版)
- 營銷數據科學:用R和Python進行預測分析的建模技術
- INSTANT Sencha Touch
- INSTANT MinGW Starter
- Building Cross-Platform Desktop Applications with Electron
- Oracle JDeveloper 11gR2 Cookbook
- FFmpeg開發實戰:從零基礎到短視頻上線
- SQL Server 2016 從入門到實戰(視頻教學版)
- HTML5移動前端開發基礎與實戰(微課版)
- Java EE架構設計與開發實踐