Reputation: 865
I am having an issue with guards within a receive, since i'm new to Erlang i have read everything i could find on this but nothing that makes it clearer for me.
The problem here is that it never checks the second guard and I don't understand why.
Have I written the guard wrong? is there another way?
receive
{ask, {guessed, N}, User} when guessed < N ->
From ! {answer, {wrong, N, lower}},
main_loop(N, update(wrong, Stats));
{ask, {guessed, N}, User} when guessed > N ->
From ! {answer, {wrong, N, higher}},
main_loop(N, update(wrong, Stats));
end.
Upvotes: 0
Views: 122
Reputation: 3584
You might got little confused there. What are you doing in your guard is comparing atom guessed
with something received and pattern-matched to N
variable. And depending on type on N
and its value, you will get true
or false
. I guess the N
is usually some number, and if you look at comparison in Erlang and those will always will be smaller than atom guessed
.
I think that what you are trying to do, is compere received N
with some value (state) that is kept in given process. Lets call this state SecretNumber
. Than your loop
could look like this.
loop( SecretNumber )
receive
%% neat pattern match, received same number as
{ask, {guessed, SecretNumber }, User} ->
User ! {answer, {right, SecretNumber}},
ok; % server will stop (finish)
{ask, {guessed, N}, User} when N < SecretNumber ->
User ! {answer, {wrong, N, lower}},
loop(SecretNumber);
{ask, {guessed, N}, User} when N > SecretNumber ->
User ! {answer, {wrong, N, higher}},
loop(SecretNumber)
end.
So you can see that first receive will execute (will pattern match as we call it) only if we receive same number as the one with which loop
was called first time.
For other receives, we bind received number to N
and than compare it to SecreteNumber
that is kept as process state.
And of course we send back message to User
(pid) from which we received guess. So User
in pattern mach will have assign a value, and to same User
than we send back a response.
Hope this help.
Upvotes: 6