codecamp

Elixir 内置协议

Elixir装载了许多内置协议.在上一章,我们讨论了​Enum​模块,任何数据结构只要实现了​Enumerable​协议就可以使用模块中提供的函数:

iex> Enum.map [1, 2, 3], fn(x) -> x * 2 end
[2, 4, 6]
iex> Enum.reduce 1..3, 0, fn(x, acc) -> x + acc end
6

另一个有用的例子是String.Chars协议,它指定了如何将字符转化为字符串.它暴露于to_string函数:

iex> to_string :hello
"hello"

注意Elixir中的字符串插值调用了​to_string​函数:

iex> "age: #{25}"
"age: 25"

上述片段能够工作是因为数字实现了​String.Chars​协议.如果传送一个元组,就会出现错误:

iex> tuple = {1, 2, 3}
{1, 2, 3}
iex> "tuple: #{tuple}"
** (Protocol.UndefinedError) protocol String.Chars not implemented for {1, 2, 3}

当需要"打印"一个更复杂的数据结构时,可以简单地使用基于Inspect协议的inspect函数:

iex> "tuple: #{inspect tuple}"
"tuple: {1, 2, 3}"

Inspect​协议的作用是约定如何将任何数据结构转化为可读的文本表示.这就是IEx用来打印结果的工具:

iex> {1, 2, 3}
{1, 2, 3}
iex> %User{}
%User{name: "john", age: 27}

记住,处于方便,如果被检查后的值以#开头,这表明着该数据结构使用了非法的Elixir语法.这意味着检查协议是不可逆的,因为信息有可能在中途丢失:

iex> inspect &(&1+2)
"#Function<6.71889879/1 in :erl_eval.expr/5>"

Elixir中还有许多协议,但以上是最普遍的.


Elixir 回退到Any
Elixir 协议巩固
温馨提示
下载编程狮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; }