[erlang-questions] newbie question of if guards

Matthias Lang matthias@REDACTED
Sun Dec 10 23:23:04 CET 2006


Chris Rathman writes:
 > I'm probably missing the obvious, but I can't figure out how to use the 
 > value of a function as a condition within an if construct.  In the 
 > sqrt_iter function below, the compiler gives me an illegal guard error - 
 > where good_enough is a function that returns a boolean.

Erlang does not allow calling arbitrary functions from guards.

One way to achieve what you're attempting below is to use 'case'
instead:

    -module(sq).
    -export([sqrt_iter/2]).
    square(X) -> X * X.
    good_enough(Guess, X) -> abs(square(Guess) - X) < 0.001.
    average(X, Y) -> (X + Y) / 2.
    improve(Guess, X) -> average(Guess, X / Guess).
    
    sqrt_iter(Guess, X) ->
       case good_enough(Guess, X) of
         true -> Guess;
         _ -> sqrt_iter(improve(Guess, X), X)
       end.

The mailing list archives and the FAQ contain some commentary as to
why Erlang restricts guards in that way.

Matthias




More information about the erlang-questions mailing list