- 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
- Dynamics 365 for Finance and Operations Development Cookbook(Fourth Edition)
- Implementing Modern DevOps
- Instant Testing with CasperJS
- 數(shù)據(jù)庫(kù)系統(tǒng)教程(第2版)
- Kubernetes實(shí)戰(zhàn)
- MySQL 8從入門到精通(視頻教學(xué)版)
- C#完全自學(xué)教程
- 控糖控脂健康餐
- Mastering Spring MVC 4
- JS全書(shū):JavaScript Web前端開(kāi)發(fā)指南
- 概率成形編碼調(diào)制技術(shù)理論及應(yīng)用
- GeoServer Beginner's Guide(Second Edition)
- Julia高性能科學(xué)計(jì)算(第2版)
- HTML5秘籍(第2版)
- R的極客理想:量化投資篇