为什么比较功能结果是Erlang中的非法防护例外? [英] Why comparing function results is an illegal guard exception in Erlang?

查看:140
本文介绍了为什么比较功能结果是Erlang中的非法防护例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是非法的?

  min1_e_(F,X,E) - > 
如果
F(X + 2 * E) F(X + E)→& %?
min1_e_(F,X,E * 2);
true - >
E
结束。我的意思是,如果我分别定义表达式的两部分,它的工作正常。但是比较函数返回应该是微不足道的,不是吗?认为我在此之下缺少一些东西。

解决方案

如果表达式在Erlang中不像其他编程语言那样工作。



根据 http://www.erlang.org/doc/reference_manual/expressions.html (第7.7段如果):


依次扫描if表达式的分支,直到找到评估为true的保护序列 GuardSeq。




在你的例子中,表达式 F(X + 2 * E) F(X + E)被视为正常表达式,但作为一个保护表达式,可能具有非确定性结果(Erlang允许在guard表达式中仅使用确定性表达式),所以Erlang拒绝在if表达式中使用它。



为了解决问题,我建议使用案例表示代替。这样的东西:

  min1_e_(F,X,E) - > 
案例F(X + 2 * E)< F(X + E)
true - > min1_e_(F,X,E * 2);
false - > E
结束。


Why is it illegal?

min1_e_( F, X, E) ->
    if 
        F( X + 2*E ) < F( X + E ) ->   % ?
            min1_e_( F, X, E*2 );
        true ->
            E
    end.

I mean, if I define both parts of expression separately, it works fine. But comparing function returns should be trivial, shouldn't it? Think I'm missing something more beneath that.

解决方案

If expression does not work in Erlang in the same way as in other programming languages.

According to http://www.erlang.org/doc/reference_manual/expressions.html (paragraph 7.7 If):

The branches of an if-expression are scanned sequentially until a guard sequence GuardSeq which evaluates to true is found.

In your example, the expression F( X + 2*E ) < F( X + E ) is treated not as a normal expression, but as a guard expression, which might have non-deterministic results (Erlang allows to use only deterministic expressions in the guard expressions), so Erlang refuses to use it in the "if" expression.

To resolve the issue, I would recommend to use a case expression instead. Something like this:

    min1_e_( F, X, E) ->
            case F(X + 2*E) < F(X + E) of
                    true -> min1_e_( F, X, E*2 );
                    false -> E
            end.

这篇关于为什么比较功能结果是Erlang中的非法防护例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆