[erlang-questions] newbie question of if guards

Chris Rathman <>
Sun Dec 10 22:55:49 CET 2006


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.

The example should be familiar as I'm trying to translate the examples 
from SICP into a number of programming languages.  I'd like to get a lot 
further along in Erlang.

http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages

Thanks,
Chris Rathman




More information about the erlang-questions mailing list