Erlang 保护式

介绍

Erlang中的保护式是一类表达式,这里不详细介绍,可以看英文资料。

, ;andalso orelse

保护式中 , andalso作用几乎相同, ; orelse作用几乎相同。这里用几乎而不是完全,理由如下。

参考资料 1

Note: I’ve compared , and ; in guards to the operators andalso and orelse. They’re not exactly the same, though. The former pair will catch exceptions as they happen while the latter won’t. What this means is that if there is an error thrown in the first part of the guard X >= N; N >= 0, the second part can still be evaluated and the guard might succeed; if an error was thrown in the first part of X >= N orelse N >= 0, the second part will also be skipped and the whole guard will fail.

However (there is always a ‘however’), only andalso and orelse can be nested inside guards. This means (A orelse B) andalso C is a valid guard, while (A; B), C is not. Given their different use, the best strategy is often to mix them as necessary.

例子:

Erlang/OTP 19 [erts-8.2] [64-bit] [smp:4:4] [async-threads:10]

Eshell V8.2  (abort with ^G)
1> F = fun() when (a-1>0) ; true -> io:format("For Fun!~n") end.
#Fun<erl_eval.20.52032458>
2> F1 = fun() when (a-1>0) orelse true ->  io:format("For Fun!~n") end.
#Fun<erl_eval.20.52032458>
3> F().
For Fun!
ok
4> F1().
** exception error: no function clause matching 
                    erl_eval:'-inside-an-interpreted-fun-'() 
5> 

由此引申出一个结论: 保护式中的异常会被当做false处理

逗号分号, ;的保护式表达式,异常的作用域是 保护式中的单个布尔运算andalso orelse的保护式表达式,异常的作用域是 整个保护式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值