[erlang-questions] newbie question of if guards
Chris Rathman
Chris.Rathman@REDACTED
Mon Dec 11 01:37:58 CET 2006
Thanks for the answers (from Mathias and Kostis)! That gets me further
along.
As long as I'm asking annoying newbie questions and I'm on the pedagogic
subject of square roots.... :-)
I'm trying to figure out the way Erlang does nested functions. From
what I gather, anonymous functions would be the way to go.
Unfortunately, I can't figure out how to make the lambda functions be
recursive, and searches for 'Erlang' and 'fun' don't narrow it down
enough. Here's what I am trying to do:
sqrt(X) ->
Good_Enough =
fun (Guess) ->
abs(square(Guess) - X) < 0.001
end,
Improve =
fun (Guess) ->
average(Guess, X / Guess)
end,
Sqrt_Iter =
fun (Guess) ->
case (Good_Enough(Guess)) of
true -> Guess;
false -> Sqrt_Iter(Improve(Guess))
end
end,
Sqrt_Iter(1.0, X).
The recursive call in Sqrt_Iter gives me an error informing me that it
is unbound. I can understand why it is unbound, but I was wondering if
there's something similar to CaML's 'rec' modifier? Or is there another
Erlang idiom for achieving this effect?
Thanks,
Chris Rathman
Matthias Lang wrote:
> Erlang does not allow calling arbitrary functions from guards.
>
> One way to achieve what you're attempting below is to use 'case'
> instead:
> ....
> Matthias
>
>
>
More information about the erlang-questions
mailing list