codecamp

Elixir 卫语句中的表达式

Elixir默认在卫语句中可以使用以下表达式:

- 比较运算符(==,!=,===,!==,>,>=,<,<=)
- 布尔运算符(and,or,not)
- 数学运算符(+,-,*,/)
- 一元运算符(+,-)
- 二进制连接符`<>`
- 当右边是一个范围或列表时,使用`in`操作符
- 下列的所有类型检查函数:
is_atom/1
is_binary/1
is_bitstring/1
is_boolean/1
is_float/1
is_function/1
is_function/2
is_integer/1
is_list/1
is_map/1
is_nil/1
is_number/1
is_pid/1
is_port/1
is_reference/1
is_tuple/1
- 加上这些函数
abs(number)
binary_part(binary, start, length)
bit_size(bitstring)
byte_size(bitstring)
div(integer, integer)
elem(tuple, n)
hd(list)
length(list)
map_size(map)
node()
node(pid | ref | port)
rem(integer, integer)
round(number)
self()
tl(list)
trunc(number)
tuple_size(tuple)

此外,用户可以定义自己的卫语句。例如,模块使用函数和操作符来定义卫语句:Bitwisebnot, ~~~, band, &&&, bor, |||, bxor, ^^^, bsl, <<<, bsr, >>>

注意,尽管例如,,的布尔操作符允许在卫语句中使用,但更常用的短路操作符,和却不被允许。andornot&&||!

记住,卫语句中的错误不会泄露,只是简单地让卫语句失败:

iex> hd(1)
** (ArgumentError) argument error
    :erlang.hd(1)
iex> case 1 do
...>   x when hd(x) -> "Won't match"
...>   x -> "Got: #{x}"
...> end
"Got 1"

如果没有语句匹配到,会抛出一个错误:

iex> case :ok do
...>   :error -> "Won't match"
...> end
** (CaseClauseError) no case clause matching: :ok

注意匿名函数也可以拥有多个卫语句:

iex> f = fn
...>   x, y when x > 0 -> x + y
...>   x, y -> x * y
...> end
#Function<12.71889879/2 in :erl_eval.expr/5>
iex> f.(1, 3)
4
iex> f.(-1, 3)
-3

匿名函数的分语句中参数的数量应当相同,否则会抛出错误。

iex> f2 = fn
...>   x, y when x > 0 -> x + y
...>   x, y, z -> x * y + z
...> end
** (CompileError) iex:1: cannot mix clauses with different arities in function definition
Elixir case
Elixir cond
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Elixir 基本操作符

Elixir 二进制,字符串和字符列表

Elixir 类型规格与行为

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }