codecamp

Elixir 标记操作符

变量在Elixir中可以被重新赋值:

iex> x = 1
1
iex> x = 2
2

当你想要对变量值进行模式匹配,而不是重新赋值时,就可以使用标记操作符:​^

iex> x = 1
1
iex> ^x = 2
** (MatchError) no match of right hand side value: 2
iex> {y, ^x} = {2, 1}
{2, 1}
iex> y
2
iex> {y, ^x} = {2, 2}
** (MatchError) no match of right hand side value: {2, 2}

由于我们已经将1赋值给变量x,最后一个例子也可以写成:

iex> {y, 1} = {2, 2}
** (MatchError) no match of right hand side value: {2, 2}

在某些情况下,你并不关心模式中特定的值。可以使用下划线将那些值捆绑起来。例如,如果我们只看重列表头,那么可以将尾赋值给下划线:​_

iex> [h | _] = [1, 2, 3]
[1, 2, 3]
iex> h
1

变量的特别之处在于它永远不可以被读取。试图读取它时会返回一个未指定变量的错误:​_

iex> _
** (CompileError) iex:1: unbound variable _

尽管模式匹配使我们能够创建强大的结构体,它的用途依旧有限。例如,你不能够在匹配的左边调用函数:

iex> length([1, [2], 3]) = 3
** (CompileError) iex:1: illegal pattern



Elixir 模式匹配
Elixir case
温馨提示
下载编程狮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; }