2

I am trying to learn erlang. Here's a basic server which calculates area of square. It is a modified version of example 6 of the erlang white paper

Here is the code:

-module(area_server).
-export([start/0, loop/0]).

start() ->
    spawn(area_server, loop, []).

loop() ->
    receive
        {Client, {square, X}} ->
            Client ! X*X,
            loop()
    end.

The problem I have is that it seems I can bind X to only one value. Binding to any other value does not work. To test, I have the following code:

Server = area_server:start().

%Works and returns 100
Server ! {self(), {square, 10}}, receive Area -> Area end.

%Does not work and just does not return at all
Server ! {self(), {square, 5}}, receive Area -> Area end.

So how can I calculate square of 5?

arahant
  • 2,203
  • 7
  • 38
  • 62
  • 2
    Ok. So it seems the problem is not in the server but in the client code. since I receive into a variable called `Area` and it is bound to 100 once, after that it cannot be bound to 25. So if I change to `Area1` in the second call, it works. – arahant Jul 16 '16 at 08:35

1 Answers1

2

What happens here is that on the second run Area is already bounded.

When you do:

recieve Area -> Area end.

The first Area receives the value, and the second Area bounds the value to the variable (Area). So after the first call Area is bounded with the value 100.
As you might already know, Erlang is a single assigment language. See this and this for more information.

When you are running this on the second time with the same Area variable, it waits on the receive call because there is no matching. The value you send is 25 but the Area inside the receive is already bounded to 100, so there is no match. That is the reason it just hangs there.

If you want this to work, you can create a function for example:

get_area(Server, Amount) ->
    Server ! {self(), {square, Amount}}, receive Area -> Area end.

And then in the client just call get_area(Server, 10) or get_area(Server, 5).

Community
  • 1
  • 1
A. Sarid
  • 3,916
  • 2
  • 31
  • 56