Elixir 基本运算详解

在上一个章节,我们看到Elixir提供了+-*/作为算数操作符,还有函数div/2rem/2用于获得整数形式的商和余数。

Elixir也提供了对列表的++--操作:

iex> [1, 2, 3] ++ [4, 5, 6]
[1, 2, 3, 4, 5, 6]
iex> [1, 2, 3] -- [2]
[1, 3]

字符串连接符是<>

iex> "foo" <> "bar"
"foobar"

Elixir也提供了三个布尔操作符:orandnot。这些操作符要求以布尔类型作为其弟一个参数:

iex> true and true
true
iex> false or is_atom(:example)
true

若第一个参数不是布尔类型则会抛出异常:

iex> 1 and true
** (ArgumentError) argument error: 1

orand是短路运算符。它们在左边不足够确定结果时才会执行右边:

iex> false and raise("This error will never be raised")
false

iex> true or raise("This error will never be raised")
true

注意:如果你是一名Erlang开发者,Elixir中的andor对应着Erlang中的andalsoorelse运算符。

除此之外,Elixir也提供||&&!操作符,它们接受任何形式的参数。在这些操作符中,除了falsenil之外的值都会被认定为真:

# or
iex> 1 || true
1
iex> false || 11
11

# and
iex> nil && 13
nil
iex> true && 17
17

# !
iex> !true
false
iex> !1
false
iex> !nil
true

推荐的做法是,当你期望布尔型时使用andornot。如果参数不是布尔型,那么使用||&&!

Elixir也提供了==!====!==<=>=<>作为比较运算符:

iex> 1 == 1
true
iex> 1 != 2
true
iex> 1 < 2
true

=====的区别在于后者对于整数和浮点数的比较更加严格:

iex> 1 == 1.0
true
iex> 1 === 1.0
false

在Elixir中,我们可以比较不同的数据类型:

iex> 1 < :atom
true

这是处于实用角度考虑。排序算法不用再担心不同的数据类型。排序定义如下:

number < atom < reference < functions < port < pid < tuple < maps < list < bitstring

你不必记住这个顺序,但需要知道它的存在。

OPERATOR    ASSOCIATIVITY
@               Unary
.               Left to right
+ - ! ^ not ~~~     Unary
* /             Left to right
+ -             Left to right
++ -- .. <>     Right to left
in              Left to right
|> <<< >>> ~>> <<~ ~> <~ <~> <|>    Left to right
< > <= >=       Left to right
== != =~ === !==    Left to right
&& &&& and      Left to right
|| ||| or       Left to right
=               Right to left
=>              Right to left
|               Right to left
::              Right to left
when                Right to left
<-, \\              Left to right
&               Unary

这些操作符中的大部分会在我们的教程中学习到。在下一章,我们将讨论一些基本函数,数据类型转换和一点点控制流。

教程来源于Github,感谢Jancd大佬的无私奉献,致敬!

技术教程推荐

算法面试通关40讲 -〔覃超〕

现代C++编程实战 -〔吴咏炜〕

Vim 实用技巧必知必会 -〔吴咏炜〕

分布式金融架构课 -〔任杰〕

高楼的性能工程实战课 -〔高楼〕

性能优化高手课 -〔尉刚强〕

程序员的测试课 -〔郑晔〕

林外 · 专利写作第一课 -〔林外〕

Serverless进阶实战课 -〔静远〕