Why comparing function results is an illegal guard exception in Erlang?

前端 未结 1 844
南方客
南方客 2021-01-12 01:56

Why is it illegal?

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


        
相关标签:
1条回答
  • 2021-01-12 02:37

    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.
    
    0 讨论(0)
提交回复
热议问题