[erlang-questions] newbie question of if guards

Kostis Sagonas <>
Sun Dec 10 23:31:53 CET 2006


Chris Rathman wrote:
> 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.
> 
> 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) ->
>    if
>       (good_enough(Guess, X)) -> Guess;
>       true -> sqrt_iter(improve(Guess, X), X)
>    end.

Unfortunately, 'if' is one of the dark corners of Erlang -- the 
expressions that can appear as part of 'if' can only be guard builtins; 
not user-defined functions as your good_enough function.

Your example can be written as:

sqrt_iter(Guess, X) ->
     case good_enough(Guess, X) of
	true  -> Guess;
	false -> sqrt_iter(improve(Guess, X), X)
     end.

My advice: try to forget that Erlang has 'if' -- things become much 
easier if you pretend you never knew 'if' existed in Erlang and its 
creator only allowed 'case' expressions.

Kostis



More information about the erlang-questions mailing list