codecamp

Elixir 抛出

在Elixir中,一个值可以被抛出然后被捕获.throwcatch是预留给那些只有它们才能检索到的值的.

这些情况很少遇到,除了当与没有提供合适的API的库相连接时.例如,想象一下Enum模块没有提供任何API来找到一个值,而我们需要从一个数字列表中找到第一个13的倍数:

iex> try do
...>   Enum.each -50..50, fn(x) ->
...>     if rem(x, 13) == 0, do: throw(x)
...>   end
...>   "Got nothing"
...> catch
...>   x -> "Got #{x}"
...> end
"Got -39"

由于​Enum​实际上 提供了合适的API,所以可以使用​Enum.find/2​:

iex> Enum.find -50..50, &(rem(&1, 13) == 0)
-39


Elixir 错误
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; }