[erlang-questions] return list or send message back

Joe Armstrong <>
Tue Oct 18 09:12:43 CEST 2011


On Mon, Oct 17, 2011 at 11:09 PM, Wes James <> wrote:
> I'm trying to learn how message passing works so I have a function
> that sends an "ls" message to another node and then when the other
> node receives it since "ls" is one of the matches for that it then
> runs a routine to list the files in a folder.  Should I build a list
> and return the results or send a message back with the results.

The first alternative is easy
 "build a list and return the results: yields the code

loop() ->
      receive
           {From, ls} ->
                 {ok, Dir} = file:get_cwd(),
                 {ok, FileNames} = file:list_dir(Dir),
                 From ! {self(), FileNames},
                 loop()
      end.

(Note: This *implies* a certain directory - so I have used
file:get_cwd() (the current working directory)
But a better interface is to accept the message {ls, Dir} rather than ls.

"send a message back with the results" - but what does "the results" mean?

Does it mean this?

loop() ->
      receive
           {From, ls} ->
                 {ok, Dir} = file:get_cwd(),
                  From ! {self(), file:list_dir(Dir)},
                  loop()
      end.

Note - you could be even *more* general - the server loop might be like this:

loop() ->
      receive
           {From, F} ->
                 From ! {self(), F()},
                 loop()
      end.


Then you send the function you want evaluating to the server in a
message like this:

Server ! {self(), fun() -> file:list_dir("/home/joe") end}

As you can see there are many ways to do things.

Which is the "best" way - there is no answer - it depends upon your
criteria for "bestness"

The one that is "easiest to debug" is probably the one that just sends
back a list of files
it's well typed and easy to understand. Sending funs (the last
alternative) is *incredibly* powerful
but can yield code that it difficult to understand and debug.

Cheers

/Joe


>
> thanks,
>
> -wes
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list