[erlang-questions] newbie question of if guards
Thomas Lindgren
thomasl_erlang@REDACTED
Mon Dec 11 15:26:12 CET 2006
--- Kostis Sagonas <kostis@REDACTED> wrote:
> 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.
Richard Carlsson has suggested a cond-operator, which
from what it seems would permit general expressions in
an if-like setting. Apart from having what I thought
was a nasty definition of variable scoping (fixable, I
expect), this sounded useful.
However, overall I think I'd really prefer simply
permitting user-defined functions in guards instead.
No, they won't have the nice properties of today's
guards (which always terminate with no side-effects),
at least not without some extra work; yes, it will be
worth it anyway, because today we have to emulate this
functionality with case-statements instead ...
(Oh, I know there are plenty of people who disagree
with this reasoning. Please don't shout :-)
Best,
Thomas
____________________________________________________________________________________
Yahoo! Music Unlimited
Access over 1 million songs.
http://music.yahoo.com/unlimited
More information about the erlang-questions
mailing list